#!/usr/bin/perl

# ARGV[0] = Host Address
# ARGV[1] = Short number of Minutes
# ARGV[2] = Short Warning
# ARGV[3] = Short Critical 

use integer; 
# Get the load from the server
$response = `/usr/local/nagios/libexec/check_nt -H $ARGV[0] -v CPULOAD -l $ARGV[1],$ARGV[2],$ARGV[3] |awk '{print \$NF}'|cut -d "%" -f 1`;
chomp $response;

# Enter the data in the rrd

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

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

# Set the exit code based on whether it is critical or not.
if ($response gt $ARGV[3]) {  
	printf ("Problem: $response% avg CPU Load over last $ARGV[1] mins (Threshold at $ARGV[3])");
        exit 2;
} else {
	printf ("$response% avg CPU Load over last $ARGV[1] mins. (Threshold at $ARGV[3])");

	# 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='cpu', value='$response', timestamp='$timestamp'";
	$sth = $dbh->query($query);
        exit 0;
}


