#! /usr/bin/perl -w

# hplj module

# Version: $Revision: 0.5 $
# Author: Mark Benvenuto
# Date: $Date: 2007/02/11 02:06:57 $
#
# Based on the SNMP module for survivor-0.9.1
# Author: Benjamin Oshrin and Matt Selsky
#
# Copyright (c) 2002 - 2007
# The Trustees of Columbia University in the City of New York
# 
# License restrictions apply, see doc/license.html for details.

use strict;
use FindBin;
use lib "$FindBin::Bin/../common";
use Survivor::Check;

use SNMP;

my %argfmt = ('community' => 'optional string default(public)',
	      'paperout' => 'optional boolean default(true)',
	      'paperjam' => 'optional boolean default(true)',
	      'tonerlow' => 'optional boolean default(true)',
	      'snmpversion' => 'optional string one(1,2,2c,3) default(1)',
	      'snmptimeout' => 'optional number between(1,inf) default(5)' );

my $sc = new Survivor::Check();

# Disable threading pending threadsafe SNMP.
$sc->UseThreads(0);

$sc->GetOpt(\%argfmt, \&HpljValidate);

unless(	$sc->Arg('paperout') || $sc->Arg('paperjam') || $sc->Arg('tonerlow') ) {
    $sc->ExitError(MODEXEC_MISCONFIG, 0,
		   "Must specify at least one of 'paperout', 'paperjam', and 'tonerlow'");
}

# Calculate timeout in microseconds

my $snmptimeout = $sc->Arg('snmptimeout') * 1000000;

my $r = $sc->Exec( \&HpljCheck);

exit($r);

sub HpljValidate {
    return(MODEXEC_OK, 0, 'Hplj OK');
}

sub HpljCheck {
    my $self = shift;
    my $host = shift;

    my $sess = new SNMP::Session( DestHost => $host,
				  Community => $self->Arg('community'),
				  UseLongNames => 1,
				  UseNumeric => 1,
				  Version => $sc->Arg("snmpversion"),
				  Timeout => $snmptimeout );

    if(!defined $sess) {
	return(MODEXEC_PROBLEM, 0, 'Unable to resolve hostname');
    }

    my $vars = new SNMP::VarList(['.1.3.6.1.4.1.11.2.3.9.1.1.2.8.0'], # paper out
				 ['.1.3.6.1.4.1.11.2.3.9.1.1.2.9.0'], # paper jam
				 ['.1.3.6.1.4.1.11.2.3.9.1.1.2.10.0'] # toner low
				 );

    my @vals = $sess->get($vars);

    foreach my $v (@vals) {
	return(MODEXEC_PROBLEM, 1, 'No response') unless(defined $v);
    }

    # Paper out
    my @errmsg;
    if( $vals[0] != 0 && $self->Arg('paperout') == 1 ) {
	push ( @errmsg, 'Paper out' );
    }
    # Paper jam
    if( $vals[1] != 0 && $self->Arg('paperjam') == 1 ) {
	push ( @errmsg, 'Paper jam' );
    }
    # Toner low
    if( $vals[2] != 0 && $self->Arg('tonerlow') == 1 ) {
	push ( @errmsg, 'Toner low' );
    }

    # We have an error
    if(@errmsg) {
	return(MODEXEC_PROBLEM, scalar @errmsg, join(', ', @errmsg) );
    } else {
	return(MODEXEC_OK, 0, 'No problems detected');
    }
}

