#!/opt/csw/bin/perl

use strict;
use Getopt::Std;
use vars qw($PROGNAME);

$PROGNAME = "check_mem";

sub usage()
{
	print <<END;
usage: $PROGNAME -c <CRITICAL> -w <WARNING>
CRITICAL and WARNING are lowest free memory in percents
or
usage: $PROGNAME -h for this help
or
usage: $PROGNAME -V for version
END
	exit 3;
}

sub get_free_mem()
{
	my @c = split(/\s+/, `kstat -p unix:0:system_pages:freemem`);
	my $f = $c[1];
	@c = split(/\s+/, `kstat -p unix:0:system_pages:pagestotal`);
	my $t = $c[1];
	if ( $t == 0 )
	{
		print "Error by getting of value of pagestotal from kstat: value is null\n";
		exit 3;
	}

	return 100*$f/$t;
}

sub main()
{

my $VER = 0.1;
my $WARN = 10;
my $CRIT = 0;
my $STATUS = 0;
my %opt=();
getopts("c:w:hV", \%opt) or usage();

usage() if defined $opt{'h'};
if (defined $opt{'V'})
{
	print "Version: $VER\n";
	exit 3;
}

$WARN = $opt{'w'} if defined $opt{'w'};
$CRIT = $opt{'c'} if defined $opt{'c'};

my $free_mem = get_free_mem();

print "MEM ";

if ( $free_mem <= $WARN )
{
	if ( $free_mem <= $CRIT )
	{
		$STATUS = 3;
		print "CRIT";
	} 
	else
	{
		$STATUS = 2;
		print "WARN";
	}
}
else
{
	print "OK";
}

printf " - Memory free %0.2f%%", $free_mem; 

if ( $CRIT > $WARN )
{
	print " (Warning: CRITICAL is greater then WARNING)";
}

print "\n";

exit $STATUS;
}
main();

