#!/usr/bin/perl

use Data::Dumper;
use Storable qw( freeze );
use LWP::UserAgent;
use Compress::Zlib;

my $info = {};
my $ua = LWP::UserAgent->new;

my $url = 'http://www.jolicloud.org/~adamm/cgi/jsh-listener.pl';

# Snarf the system's DMI table
chdir "/sys/devices/virtual/dmi/id";
foreach my $f ( <*> ) {
    next unless $f =~ /_/;
    chomp $f;

    open( DMI, $f );
    while( <DMI> ) {
        chomp;
        $info->{ 'dmi' }->{ $f } .= $_;
    }
    close( DMI );
}

# Read lspci's raw output
my $pci = {};
foreach ( `lspci -nn -v` ) {
    chomp;
    if ( /^(.......) .*? \[(....)\]: .*? \[(....):(....)\]/ ) {
        if ( $pci->{ 'slot' } ) {
            $info->{ 'lspci' }->{ $pci->{ 'slot' } } = $pci;
            $pci = {};
        }
        $pci = {
            slot => $1,
            class => $2,
            vendor => $3,
            device => $4,
        };
    }
    elsif ( /Subsystem: .*? \[(....):(....)\]$/ ) {
        $pci->{ 'svendor' } = $1,
        $pci->{ 'sdevice' } = $1,
    }
    elsif ( /Kernel driver in use: (.*?)$/ ) {
        $pci->{ 'driver' } = $1,
    }
    elsif ( /Kernel modules: (.*?)$/ ) {
        $pci->{ 'modules' } = $1,
    }
}
if ( $pci->{ 'slot' } ) {
    $info->{ 'lspci' }->{ $pci->{ 'slot' } } = $pci;
}

# Read lsusb's raw output
foreach ( `lsusb` ) {
    chomp;
    if ( /ID (....):(....) / ) {
        push( @{ $info->{ 'lsusb' } }, {
            vendor => $1,
            product => $2,
        } );
    }
}

# Read the CPU's stats
my $processors = 1;
foreach ( `cat /proc/cpuinfo` ) {
    chomp;
    my ( $key, $val ) = split( ": " );
    $key =~ s/\s+$//;

    next if ( ! $key || ! $val );

    if ( $key eq "processor" ) {
        $processors++;
    }
    else {
        $info->{ 'cpuinfo' }->{ $key } = $val;
    }
}
$info->{ 'cpuinfo' }->{ 'processors' } = $processors;

# Identify running modules
foreach ( `cat /proc/modules` ) {
    chomp;
    if ( /^(.*?) \d.* (\d+) (.*?),? Live 0x/ ) {
        my $used = $3;
        $info->{ 'lsmod' }->{ $1 } = {
            count => $2,
            used  => $used,
        };
    }
}

# Grab information about the soundcard
my $control;
foreach ( `amixer` ) {
    chomp;
    if ( s/^Simple mixer control // ) {
        $control = $_;
    }
    if ( s/^  // ) {
        my ( $key, @val ) = split( ": " );
        my $val = join( ": ", @val );
        next unless ( $key && $val );
        $info->{ 'amixer' }->{ $control }->{ $key } = $val;
    }
}

# Set the product_uuid as the key
$info->{ 'uuid' } = $info->{ 'dmi' }->{ 'product_uuid' };


$data = compress( freeze( $info ) );
if ( $status != Z_OK ) {
    die "Zlib error: $status";
}

$data =~ s/(\W)/sprintf "%%%02x", ord $1/ge;

#
# Send the data
#

my $req = HTTP::Request->new( POST => $url );
$req->content_type( "application/x-www-form-urlencoded" );
$req->content( "data=$data" );

my $res = $ua->request( $req );

#print $res->content . "\n";

if ( $res->content ne "OK" ) {
    exit 1;
}
exit 0;

