#!/usr/bin/perl
# dfmail: df $@$7$F%G%#%9%/$,0lGU$K6a$1$l$P%a!<%k$9$k!#(B
#         $@DL>o!"(B cron $@$+$i5/F0$7$F;H$&!#(B
# $@G[I[$O(B GPL $@$K$7$?$,$C$F9T$C$F$/$@$5$$!#(B
# Copyright (C) 1998, by Seio ODA(oda@fjct.fit.ac.jp), Allrights reserved.
# usage: dfmail [-m mailaddr][-if] fsys:warn:alart:full ...
# options:
#  -m mailaddr : mail addres
#  -f: $@%G%#%9%/$KLdBj$,$J$/$H$b$H$K$+$/%a!<%k$r=P$9!#(B
#  -i: $@LdBj$N$J$$%G%#%9%/$OL5;k(B(-f $@$N$H$-L58z(B)
# parameters:
#  fsys:warn:alart:full
#  fsys $@$K%^%&%s%H$5$l$?%G%#%/%9$KBP$9$k!"Cm0U!"7Y9p!"=*Kv%l%Y%k$N;XDj(B
#  $@Nc(B: /home:80:90:100
#    /home $@$,(B80%$@$r1[$($?$iCm0U(B, 90%$@$r1[$($?$i7Y9p(B, 100%$@$r1[$($?$i$*$7$^$$(B
#  fsys $@$K2?$b;XDj$7$J$$$HA4$F$N%G%#%9%/$KE,1~$5$l$k!#(B

require 'getopts.pl';

&Getopts('fim:');

$mailto = 'root';
$mailto = $opt_m if $opt_m;
chop($hostname = `hostname`);

$df = '/bin/df';
$mail = '/bin/mail';	# /usr/bin/mail on BSD/OS

@Subject = 
    ("[DISK INFO] $hostname disk(s) has enough space.",
     "[DISK WARNING] $hostname disk(s) is short.",
     "[*DISK ALART*] $hostname disk(s) is nearly full.",
     "[**DISK FULL**] $hostname disk(s) is full up.",
     "[*************] $hostname disk(s) something wrong!!.");

for(@ARGV) {
    ($root,$wpar,$apar,$fpar) = split(/\:/,$_);
    next unless $fpar;
    if($root) {
	$fsys{$root} = [$wpar,$apar,$fpar,1000];
    } else {
	@fsys = ($wpar,$apar,$fpar,1000);
    }
}

$alevel = 0;

open(DF,"$df |") || die("$df: $!");
$message = <DF>;
while(<DF>) {
    ($dp,$all,$use,$avail,$cap,$mount) = split; $line = $_;
    if(($fs = $fsys{$mount}) || (@fsys && ($fs = \@fsys))) {
	if($a = alevel($fs,$cap)) {
	    $alevel = $a if($a > $alevel);
	    chop $line;
	    $message .= $line . " <--\n";
	} elsif($opt_f || !$opt_i) {
	    $message .= $line;
	}
    } elsif($opt_f) {
	$message .= $line;
    }
}
close DF;

if($alevel>0 || $opt_f) {
    open(M,"| $mail -s \'$Subject[$alevel]\' $mailto") || die("$mail: $!");
    print M $message;
    close M;
}

exit 0;

sub alevel {
    my ($d,$p) = @_;
    my $i;

    for($i = 0; $i < 4; $i++) {
	return $i if($p < $$d[$i]);
    }
    return 4;
}
