#!/usr/bin/perl

# ARGV[0] = Host Address
# total = Total Memory
# used = Used Memory
# percentused = Percent Memory Used

# Get the memory stats from the server
$response = `/usr/local/nagios/libexec/check_nt -H $ARGV[0] -v MEMUSE`;

# Get the total value
$totalchars = (index($response, "used:") - 26);
$total=substr($response, 20, $totalchars);
chomp $total;

# Get used value
$usedend = (index($response, "free:") - (index($response, "used:") + 5) -13);
$used = substr($response, (index($response, "used:")+6), $usedend);
chomp $used;

$percentused = sprintf "%.2f", ($used/$total)*100;


# Enter the data in the rrd

#$rrdentry = "/usr/bin/rrdtool update /usr/local/httpd/htdocs/cacti/rra/$ARGV[0]mem.rrd N:$percentused";
#system $rrdentry;

$rrdentry1 = "/usr/bin/rrdtool update /usr/local/nagios/rrd/$ARGV[0].rrd -t mem N:$percentused";
system $rrdentry1;

# Set the exit code based on whether it is critical or not.
if ($response) {  
	printf ("$used Mb out of $total Mb Memory Used ($percentused\%)");
        # Record value in MySQL
        use Mysql;

        # Set timestamp to current date/time I know there's a function for this but I can't find it!!
        $timestamp=sprintf "%4d-%02d-%02d %02d:%02d:%02d",
                (localtime)[5]+1900,
                (localtime)[4]+1,
                (localtime)[3,2,1,0];

        $dbh = Mysql->connect("localhost", "itweb", "mysql", "mysql", "servervalues");
        $query = "INSERT INTO servervalues SET name='$ARGV[0]', valuetype='memtotal', value='$total', timestamp='$timestamp'";
        $sth = $dbh->query($query);
        $query = "INSERT INTO servervalues SET name='$ARGV[0]', valuetype='memused', value='$used', timestamp='$timestamp'";
        $sth = $dbh->query($query);

        exit 0;
} else {
#	printf ("Problem: Could NOT connect to Server");
        exit 2;
}


