#!/usr/bin/perl 
#
# diskfull - check for "full" disks, mailing top users about the problem
# tom christiansen, 9-sep-90
#
# "full" is defined as having more than $MIN_FREE percent usesd,
# unless the file system is mentioned in the $EXCEPT file, which
# should consist of ordered pairs of filesystems and minfree values.

$MIN_FREE  = 97;	# unless in EXCEPT file, want this much free
$MIN_WHINE = 5; 	# don't whine at someone with less than this %

$EXCEPT    = '/usr/adm/etc/capacities';

chop($hostname = `hostname`);

&read_exceptions;

open(DF, "df -t 4.2|");
$_ = <DF>; 		# skip header
while ( <DF> ) {
    chop;
    ($disk, $kbytes, $used, $avail, $capacity, $mpnt) = split;
    $capacity =~ s/%//;
    if ( $capacity > (defined($Max{$mpnt}) ? $Max{$mpnt} : $MIN_FREE)) {
	&too_full($mpnt, $used, $capacity);
    } 
} 
close DF;
exit;

# ---------------------------------------------------------------------------

sub read_exceptions {
    local($fs, $min_free);
    # global $EXCEPT %Max

    if (-e $EXCEPT) {
	open EXCEPT || die "can't open $EXCEPT: $!";
	while ( <EXCEPT> ) {
	    next if /^\s*#/ || /^\s*$/;
	    chop;
	    ($fs, $min_free) = split(' ');
	    if ($fs =~ /^min_?free/i) {
		$MIN_FREE = $min_free;
	    } else {
		$Max{$fs} = $min_free;
	    } 
	} 
	close EXCEPT;
    } 
}

# ---------------------------------------------------------------------------

sub too_full {
    local($fs, $kused, $percen) = @_;
    local($_, $used, $user, $anon, @anon, @lines, @allusers, @abusers);

    open (QUOT, "/usr/etc/quot $fs|");
    $_ = <QUOT>;  # skip header

    while ( <QUOT> ) {
	push(@lines, $_);
	chop;
	($used, $user) = split(' ');
	if ($user =~ /^#/) {
	    push(@anon, $user);
	    $anon =+ $used;
	    next;
	} 
	push(@allusers, $user);
	push(@abusers, $user) 	unless $used/$kused < ($MIN_WHINE/100);
    } 
    close QUOT;
    die "couldn't run quot on $fs" if $? || $#allusers < 0;

    $rcpts = join(", ", ($#abusers < 0) ? @allusers : @abusers);

    if (0 && $anon) { # maybe someday
	print "Should remind root that $anon kbytes on $fs are used by ";
	print "defunct users ", join(', ', @anon), "\n";
    } 

    open (MAIL, "| /usr/lib/sendmail -oi -t");
    select(MAIL);

    print <<EOM;
From: the Disk Monitor Daemon ($0) <daemon>
To: $rcpts
Cc: root
Subject: $fs on $hostname is $percen% full

Each of you is taking up at least $MIN_WHINE% of the space on $hostname:$fs.
Please do what you can to reduce this.  You might consider simply removing
extraneous files, moving some files to other filesystems, compressing them, 
or backing them up on tape and then deleting them.

your friend, the daemon

PS: here are the exact totals in kilobytes for top users:

EOM

    print @lines[0..$#abusers];
    print "\n";
    close MAIL;
    select(STDOUT);
}