#!/usr/bin/perl
use DBI;
# Nagios Error Codes
my %ERRORS = ('UNKNOWN', '3',
                'OK', '0',
                'WARNING', '1',
                'CRITICAL', '2');

my %INT_STATUS = ('2', 'DOWN',
			'1','UP');

# For the better handle
my $host_ip = @ARGV[0];
my $community = @ARGV[1];
my $interface_ip = @ARGV[2];
my $expect = @ARGV[3];
my $snmp_id = NULL;

# Check if all Parameters were given
sub check_args {
 if (@ARGV[0] eq "help") {
  print "\n";
  usage();
  print "\nIn Future you can read here some Help.\n\n";
  print "\nFor more Information please contact me under: <h.baecker@ecofis.de>\n\n";
  exit 0;
 }
 if (!@ARGV[0]||!@ARGV[1]||!@ARGV[2]||!@ARGV[3]){
  print "$0 - Could not parse arguments\n";
  usage();
  exit -1;
 }
}

# Check if there is a cache entry in the DB
sub check_if_cache_exists {
	$result = $dbh->prepare("SELECT * FROM `cisco-interface-cache` WHERE host_addr='$host_ip' AND interface_addr='$interface_ip';");
	$result->execute();
	 while ($row=$result->fetchrow_hashref) {
	  if ($row->{'host_addr'}) {
	    $cache_exists=1;
	    $snmp_id = $row->{'interface_snmp_id'};
	  }
	 }
 	$result->finish();
}

# Connect to the DB
sub database_connect
{
  $dbh = DBI->connect("DBI:mysql:database=nagios-snmp-cache;host=localhost", "nagios", "nagios", { RaiseError => 1, AutoCommit => 1});
}

# Disconnect from DB
sub database_disconnect
{
  $dbh->disconnect();
}


# SNMPGET to the Host, asking for the real SNMP ID and the ifOperStatus
# If cached SNMP ID differs from real SNMP ID then update DB and exit with WARNING.
# else: Check if the OperStatus is what we want to see and exit.
#

sub getOperStatus { 
 $line=`snmpget -Oeq -c $community -v 1 $host_ip IP-MIB::ipAdEntIfIndex.$interface_ip IF-MIB::ifOperStatus.$snmp_id`;
 if ($line=~/^.*\ (\d*)\n.*\ (\d*)/) {
   $operStatus="Operating Status: ".$INT_STATUS{$2};
   if ($snmp_id != $1) {
      $result = $dbh->prepare("UPDATE `cisco-interface-cache` SET interface_snmp_id='$1' WHERE host_addr='$host_ip' AND interface_addr='$interface_ip';");
      $result->execute();
      print "Warning: ID has Changed - DB must be updated - ID should be: $1\n";
      exit $ERRORS{WARNING};
   }
   else {
      ## ID has not changed - check if this is what we want to see
      if ($expect==$2) {
	print "OK - $operStatus\n";
          exit $ERRORS{OK};
      }
      else {
	print "CRITICAL - $operStatus\n";
	exit $ERRORS{CRITICAL};
      }
   }
 }
}

# Print Usage:
sub usage {
	print "Usage: $0 <HOST-Adress> <SNMP-COMMUNITY> <INTERFACE-IP-ADRESS> <EXPECT>\n";
	print "Example: $0 192.168.0.1 READ_COMM 192.168.5.110 1\n";
}

check_args;
database_connect();
check_if_cache_exists;
if ($cache_exists==1) {
  getOperStatus; #Checks for Cache Updates and Checks the Operating Status
  }
else {
  $result = $dbh->prepare("INSERT INTO `cisco-interface-cache` values \('$host_ip','$interface_ip','1'\);");
  $result->execute();
  $snmp_id=1;
  getOperStatus;
}
database_disconnect();
