#!/usr/bin/perl -w
#
# Copyright (c) 2000-2004 University of Utah and the Flux Group.
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file 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 Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
use Getopt::Std;
use English;
use Errno;
use POSIX qw(strftime);

#
# PLAB rusage probe.  Returns a TMCD-style string suitable for returning
# to...TMCD!
#
sub usage()
{
    print STDERR "Usage: plabrusage\n";
    exit(1);
}
my $optlist = "";

#
# Turn off line buffering on output
#
$| = 1;

# Drag in path stuff so we can find emulab stuff.
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }

#
# Load the OS independent support library. It will load the OS dependent
# library and initialize itself. 
# 
use libsetup;
use libtmcc;

# Locals
my $logname	= "$LOGDIR/plabusage.log";
my $stats	= "";

#
# Parse command arguments. Once we return from getopts, all that should be
# left are the required arguments.
#
%options = ();
if (! getopts($optlist, \%options)) {
    usage();
}

#
# Must be root.
# 
if ($UID != 0) {
    die("*** $0:\n".
	"    Must be root to run this script!\n");
}

#
# Get the load average. Linux only right now.
#
if (open(LA, "/proc/loadavg")) {
    $_ = <LA>;

    if ($_ =~ /^([\d\.]+)\s+([\d\.]+)\s+([\d\.]+)\s+.*$/) {
	$stats .= " LA1=$1 LA5=$2 LA15=$3";
    }
    else {
	print STDERR "Could not parse loadav: $_";
	exit(1);
    }
    close(LA);
}
else {
    print STDERR "Could not open /proc/loadav: !$\n";
    exit(1);
}

#
# Grab disk usage.
#
if (open(DF, "df -P -k -l / |")) {
    my $du = "";

    # Consume all output ...
    while (<DF>) {
	next
	    if ($_ =~ /^filesystem.*/i);
	
	if ($_ =~ /^[-\w\.\/]+\s+\d+\s+\d+\s+\d+\s+(\d+)%\s+([-\w\.\/]+)$/) {
	    if ($2 eq "/") {
		$du = " DUSED=$1";
	    }
	}
    }
    close(DF);

    # XXX tmcd expects something to be reported
    $du = " DUSED=100"
	if ($du eq "");

    $stats .= $du;
}
else {
    print STDERR "Could not start df process: !$\n";
    exit(1);
}

print $stats;

exit(0);
