#!/usr/bin/perl
#
# Monitor disk space usage
#
# Arguments are:
#
# path:kBfree [path:kBfree...]
# or
# path:free% [path:free%...]
#
# This script will exit with value 1 if "path" has less than
# "kBfree" kilobytes, or less than "free" percent available.
#
# The first output line is a list of the paths which failed, and
# how much space is free, in megabytes.
#
# If you are testing NFS-mounted directories, should probably
# mount them with the ro,intr,soft options, so that operations
# on those mount points don't block forever if the server is
# down, and I may eventually change this code to use an alarm(2)
# to interrupt the stat and statfs system calls.
#
#### Jason Castonguay jcastonguay@solfopro.com
# 
# Jim Trocki, trockij@transmeta.com
#
# $Id: freespace.monitor 1.2 Tue, 26 Dec 2000 04:45:04 -0500 trockij $
#
#    Copyright (C) 1998, Jim Trocki
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
use Filesys::DiskFree;

foreach (@ARGV) {
    ($path, $minavail) = split (/:/, $_, 2);
    
    $handle = new Filesys::DiskFree;
    $handle->df();
    $used = $handle->used($path);
    $avail =$handle->avail($path);


    if (!defined ($used)) {
	push (@failures, "statfs error for $path: $!");
	next;
    }

    if ($minavail =~ /(\d+(\.\d+)?)%/o) {
    	$minavail = int(($used + $avail) * $1 / 100);
    }

    if ($avail < $minavail) {
    	push (@failures, sprintf ("%1.1fGB free on %s", $avail / 1024 / 1024 /1024,
	    $path));
    }
}

if (@failures) {
    print join (", ", @failures), "\n";
    exit 1;
}

exit 0;
