#!/usr/bin/perl -wT

#
# $Id: check_rrd_data.pl,v 1.1 2004/08/27 16:19:09 hmann Exp $
#
# check_rrd_data plugin for nagios
#
# usage:
#    check_rrd rrdfile [ds] warning critical
#
# Copyright Notice: GPL
#

require '/usr/local/nagios/libexec/utils.pm';
#makes things work when run without install
use lib qw( ../perl-shared/blib/lib ../perl-shared/blib/arch );
# this is for after install
use lib qw( /usr/local/rrdtool-1.0.45/lib/perl ../lib/perl );
use RRDs;
use strict;			# RRD:File and utils.pm don't like this

$ENV{'PATH'} = "/bin:/usr/bin";
$ENV{'ENV'} = "";

if (scalar @ARGV != 4 && scalar @ARGV != 5) {
	print STDERR join "' '", @ARGV, "\n";
	my $foo = 'check_rrd_data';
	exit;
}

# Default
# Guess which RRD file have to be opened
my $rrdfile = $ARGV[0] if (-r $ARGV[0]);		# First the parameter
	print "\$rrdfile = $rrdfile\n";

my $ds = defined $ARGV[1]?$ARGV[1]:0;
	print "\$ds = " . $ds . "\n";
$ds =~ s/\$//g;		# Sometimes Nagios gives 1$ as the last parameter

my $warn = defined $ARGV[2] ? $ARGV[2] : 0;
#	print "\$warn = " . $warn . "\n";

my $crit = defined $ARGV[3] ? $ARGV[3] : 0;
#	print "\$crit = " . $crit . "\n";

my ($last) = RRDs::last ($rrdfile);
 print "\$last: ","$last\n";

my ($start,$step,$names,$data) = RRDs::fetch ($rrdfile,"AVERAGE","-s",$last,"-e",$last);
$last = $start;
($start,$step,$names,$data) = RRDs::fetch ($rrdfile,"AVERAGE","-s",$last,"-e",$last);
#  print "Start:       ", scalar localtime($start), " ($start)\n";
#  print "Step size:   $step seconds\n";
#  print "DS names:    ", join (", ", @$names)."\n";
#  print "Data points: ", $#$data + 1, "\n";
#  print "Data:\n";
#  foreach my $line (@$data) {
#    print "  ", scalar localtime($start), " ($start) ";
#    $start += $step;
#    foreach my $val (@$line) {
#      printf "%12d ", $val;
#    }
#    print "\n";
#  }

my $i;
my $found_index;
for ($i= 0; $i < @$names; $i++) {
	if (@$names[$i] eq $ds) {
	    $found_index = $i;
            last;
	}
}
my $value = @$data[0]->[$found_index];
 print "DS Index: %d value: %s\n", $found_index, "$value";

# First check for critical errors
if ($value > $crit) {
	print "RRD CRITICAL ", "$ds:", " $value\n";
	exit 2;		# Critical
}

# Check for warnings
if ($value > $warn) {
	print "RRD WARNING ", "$ds:", " $value\n";
	exit 1;		# Warning
}

# Normally returns 0 (OK)
print "RRD Check OK ", "$ds:", " $value\n";
exit 0
