#!/usr/bin/perl

#
# inverse check_snmp for nagios - need to support snmp3 opts
# and verbose
#
# intentionally compatible with the standard nagios check_snmp
# plugin, but with the number sense (for -c and -w) inverted
# i.e. low values more critical than high values
#
# this is really just a wrapper to snmpget
#

use strict;
use Getopt::Std;
use Data::Dumper;
use vars qw/$opt_m $opt_M $opt_w $opt_c $opt_C $opt_v $opt_H $opt_o/;

# exit codes - from nagiosplug.sf.net docs
my %exit = ( ok       => 0,
	     warning  => 1,
	     critical => 2,
	     unknown  => 3);
########################################################################
sub usage {
    # summarise command line options
    print "
usage: $0 [ -m miblist| -M mibdir | -w warn level | -c critical level |
-C community -v snmp version]
-H address -o oid
";
    exit($exit{unknown});
}
########################################################################
# get options and exit if we don't have enought to work with
getopt('mMwcCHo');

unless ($opt_H and $opt_o) { usage }

# hmmm, must have enough to work with for now
# options for snmpget
my $cmdline = 'snmpget ' . $opt_H . ' ';
if ($opt_m) { $cmdline .= '-m ' . $opt_m . ' ' }
if ($opt_M) { $cmdline .= '-M ' . $opt_M . ' ' }
if ($opt_C) { $cmdline .= '-c ' . $opt_C . ' ' }
if ($opt_v) { $cmdline .= '-v ' . $opt_v . ' ' }

$cmdline .= ' ' . $opt_o;

# can now run snmpget with these options
my @response = qx/$cmdline/;
# numeric exit code from snmpget is in $?  <- who thinks up these
# variable names anyway?
if ($? ne 0) {
    print "Problem executing $cmdline: $!";
    exit($exit{unknown});
}

# return the response unless -w or -c specified
unless ($opt_w or $opt_c) {
    my @ret = split(/=/, shift(@response));
    print 'SNMP OK - ', $ret[1];
    exit($exit{ok});
}


# have a warning or critical threshold
my $resp = shift(@response);
chomp $resp;

# warning and crit can only be numeric - exit if they're not
unless ($resp =~ /\d*/) {
    print "SNMP CRITICAL - $resp is non-numeric";
    exit($exit{critical});
}

# valid numeric response
chop $resp;
$resp = chop $resp;
if ($resp <= $opt_c) {
    print "SNMP CRITICAL - $resp";
    exit($exit{critical});
} elsif ($resp <= $opt_w) {
    print "SNMP WARNING - $resp";
    exit($exit{warning});
} else {
    print "SNMP OK - $resp";
    exit($exit{ok});
}
