#!/usr/bin/perl

# monMem  (c) Copyright 1998 Mark Black
 
# NOTE:  If you modify this code, you MUST change the version to
#        something over 100 to prevent it being replaced by future
#        versions of this script. 
$version = 2 ;

# monMem [-v|-i]
# This script monitores memory use on the supported platforms
# Outputs status to stdout in the form  status:info
# status can be 0 or 1.  1 = success, 0 = fail
# NOTE:  The script should not have a reason to output a fail
# The info is in the form:    Total_memory:Used_memory
#   -v  - Output the version number
#   -i  - Output a list of the instances of network interfaces

$input = "" ;
foreach $i (0 .. $#ARGV) {
   $input .= "@ARGV[$i] " ;
}
chop($input) ;

# Location of MAT tmp dir
$mattmp = "tmp" ;

# Output the version if requested
if($input eq "-v") {
    print "$version\n" ;
    exit(0) ;
}


# Discover OS type and set variables for OS type
chop($os = `uname -s`) ;

if($os eq "Linux") {
    $dfile = "/proc/meminfo" ;
    $instance = 0 ;	
    if( -e $dfile && -r $dfile ) {
	# Proc filesystem  exists and is readable
	$instance = 1 ;
    }
    $OS="linux" ;
} elsif($os eq "SunOS") {
    chop($ver = `uname -r`) ;
    ($major, $minor) = split(/\./, $ver) ;
    if($major == 5) {
	$instance = 0 ;	
	$OS = "solaris" ;
    } else {
	$instance = 0 ;	
	$OS = "sunos" ;
    }
} elsif(($os eq "IRIX") | ($os eq "IRIX64"))  {
	$instance = 0 ;	
    $OS = "irix" ;
} elsif($os eq "HP-UX") {
	$instance = 0 ;	
    $OS = "hpux" ;
}

# Output the instance if requested
if($input eq "-i") {
    print "$instance:\n" ;
    exit(0) ;
}

if($OS eq "linux") {
    # Pull the data out of the proc filesystem  (It's just so handy)
    $ext = open(DTFILE, $dfile) ;
    if ($ext) {
	@din = <DTFILE> ;
	close DTFILE ;
    } else {
	# Read failed!
	print "0:1:1\n" ;
	exit 0 ;
    }
    $memt = 0 ;
    $memu = 0 ;
    foreach $line (@din) {
	chop($line) ;

	if( $line =~ /^SwapTotal:.*/ ) {
	    # Grab the total swap
	    $line =~ s/^SwapTotal:\s+(\d+)\s*kB/$1/ ;
	    $memt = $line ;
	}

	if( $line =~ /^SwapFree:.*/ ) {
	    # Grab the free swap
	    $line =~ s/^SwapFree:\s+(\d+)\s*kB/$1/ ;
	    $memu = $memt - $line ;
	}
    }

    if( $memt != 0) {
	# Output results
	print "1:$memt:$memu\n" ;
    }
    
}    

exit 0 ;


