#!/usr/bin/php -q
<?php
// Script to check remote apt-get via SNMP
// Uses check_apt from the nagios plugins package: http://nagiosplug.sourceforge.net/
// Exit Errorlevels: 0=OK, 1=Warning, 2=Critical, 3=Unknown

// Help information
$help = "Apt-get snmp check plugin for nagios\n" .
        "----------------------------------\n" .
        "Usage: remote-check_apt -H <host> [-p <port>] -C community\n" .
        "--help\n" .
        "  print this help message\n" .
        "-H\n" .
        "  name or IP address of host to check\n" .
        "-C\n" .
        "  SNMP community\n" .
        "-p\n" .
        "  SNMP port number (optional, defaults to 161)\n";

// Print help if no argument is specified
if ($argc <= 1) {
  fwrite(STDOUT,$help);
  exit(0);
}

$options = getopt("h:H:p:C:");

if ($options['h']) {
  fwrite(STDOUT,$help);
  exit(0);
} 

if ($options['H']) {
  $snmphost = $options['H']; 
} else {
  fwrite(STDOUT,"Missing hostname/ip (-H)\n");
  exit(3);
}

if ($options['p']) {
  $snmpport = $options['p']; 
} else {
  $snmpport = "161";
}

if ($options['C']) {
  $snmpcommunity = $options['C']; 
} else {
  fwrite(STDOUT,"Missing SNMP Community (-C)\n");
  exit(3);
}

// set snmpoid variable for the custom commands
$snmpoid = ".1.3.6.1.4.1.2021.8";
snmp_set_oid_numeric_print(TRUE);
snmp_set_quick_print(TRUE);
snmp_set_enum_print(TRUE);

$rawsnmp = 	@snmprealwalk($snmphost, $snmpcommunity, $snmpoid) or 
			// exit with UNKNOWN error level
			fwrite(STDOUT,"Could not get data from host $snmphost\n") and exit(3);

foreach($rawsnmp as $oid => &$output) {
	//Find command SNMP OID
	if (eregi('aptgetsnmp',$output)) {
		$id = substr(strrchr($oid, "."), 1);
	}
}

if (is_numeric($id)) {
	$exitlevel 	= $rawsnmp[".1.3.6.1.4.1.2021.8.1.100.$id"];
	$output 	= $rawsnmp[".1.3.6.1.4.1.2021.8.1.101.$id"];
	fwrite(STDOUT,"$output\n");
	// Exit with errorelevel got by snmp result, using intval so exit won't treath it as a string
	exit(intval($exitlevel));
	
} else {
	// exit with UNKNOWN error level
	fwrite(STDOUT,"Could not find aptget in $oid, check your snmpd.conf on $snmphost\n");
	exit(3);
}

?>
