#!/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_df.pl "ssh -i ~cricket/.ssh/df target.host" /mount_point
#		ssh into remote host and get data for /mount_point
#
# 	parse_df.pl "ssh -i ~cricket/.ssh/df target.host" --config
# 		dump configuration file to stdout
#

use strict;

my $ssh = shift @ARGV || "";
my $mount = shift @ARGV || "/";

# do we have Cache::FileCache installed?

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

my $df;

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

sub parse_df {
	my $ssh = shift @_;
	if ($USE_CACHE) {
		print STDERR " [using cache] ";
		$df = $cache->get( $ssh );
		return if (defined $df);
		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 df -klP |") || die "$ssh df: $!";
	};
	print STDERR " read DF eof=",eof(DF);
	while(<DF>) {
		chomp;
		my ($node,$total,$used,$aval,$use_pcnt,$mount) = split(/\s+/,$_,6);
		if ($use_pcnt && $use_pcnt =~ s/(\d+)%/$1/) {
#			print STDERR "$_\n";
#			$df->{$mount}=$use_pcnt;
			$df->{$mount}=$used * 100 / $total if ($total != 0);
#			print $df->{$mount}," == $use_pcnt\n";
		}
	}
	close(DF);
	alarm 0;	# turn alarm off
	$cache->set( $ssh, $df, "1 min" ) if ($USE_CACHE);
}

parse_df($ssh);

if ($mount eq "--config") {
	print <<"EOF";
target --default--
	ssh		=	"$ssh"
	long-desc	=	"edit name of your host here"

EOF
	my @targets;

	foreach my $mnt (keys %{$df}) {
		my $target = $mnt;
		if ($mnt eq "/") {
			$target = "root";
		} else {
			$target =~ s,^/,,;
			$target =~ s,/,_,g;
		}
		push @targets,$target;
		print <<"EOF";
target	$target
	target-type	=	usage
	display-name	=	"$mnt"
	skip-overview	=	1

EOF
	}
	print "target overview
	mtargets	= \"",join("; ",@targets),"\"
	target-type	= usage
	y-min		= 0
	y-max		= 100\n";
	exit 1;
}

# dump free %
#
print $df->{$mount} || "unknown";
print "\n";
