#!/usr/bin/perl -w
#
# cricket module which creates configuration file (when called with
# apropriate option), re-reads configuration (so that it can report
# filesystems in same order always)
#
# Dobrica Pavlinusic <dpavlin@rot13.org>
# http://www.rot13.org/~dpavlin/sysadm.html
#
# Usage:
#
# 	parse_wifi.pl "ssh -i ~cricket/.ssh/wifi target.host" /mount_point
#		ssh into remote host and get data for /mount_point
#
# 	parse_wifi.pl "ssh -i ~cricket/.ssh/wifi target.host" --config
# 		dump configuration file to stdout
#

use strict;

my $ssh = shift @ARGV || "";
my $dev = shift @ARGV;

# do we have Cache::FileCache installed?

my $USE_CACHE = 0;
eval("use Cache::FileCache;");
if (! $@) { $USE_CACHE = 1; }

my $wifi;
my @labels;

my $cache = new Cache::FileCache() if ($USE_CACHE);

if ($USE_CACHE) {
	print STDERR " [using cache] ";
	$wifi = $cache->get( $ssh );
	return if (defined $wifi);
	print STDERR " [cache miss] ";
}
eval {
	local $SIG{ALRM} = sub { die "ssh timeout\n"; };
	alarm 10;	# wait for ssh to connect and return first line
	open(DF,"$ssh cat /proc/net/wireless /proc/net/dev |") || die "$ssh wifi: $!";
};
while(<DF>) {
	chomp;
	s/\|//g;		# remove | delimiters
	my @arr = split(/[\s:]+/,$_);
	shift @arr;	# dump first element -- empty one

	# store labels
	if ($arr[0] eq "face") {
		shift @arr;
		push (@labels,@arr);
	}

	if ($#arr == 10) {	# /proc/net/wireless
		if (! $dev && $arr[0]) {
			$dev = $arr[0];
		}
		if ($dev && $arr[0] eq $dev) {
			shift @arr;
			push @{$wifi->{$dev}},@arr;
		}
	} elsif ($#arr == 16 && $arr[0] eq $dev) {	# /proc/net/dev
		shift @arr;
		push @{$wifi->{$dev}},@arr;
	}
}
close(DF);
alarm 0;	# turn alarm off
$cache->set( $ssh, $wifi, "1 min" ) if ($USE_CACHE);

# dump
for(my $i=0; $i <= ($#labels+1); $i++) {
#	print $labels[$i]," [$i] : ";
	my $val = $wifi->{$dev}[$i];
	$val =~ s/\.$//g;		# kill trailing dot
	print $val || 0;
	print "\n";
}

