#!/usr/bin/perl
use Getopt::Long;

#
# README FIRST
# 
# This script was tested with success agains following printers:
#  - Lexmark T644 version NC2.NPS.N211 kernel 2.6.10 All-N-1
#
#
# WARNING
# For printers like OKI OkiLAN 8300e try to use check_oki_printer.pl
#

$snmpget = "/usr/bin/snmpget";
$snmpwalk = "/usr/bin/snmpwalk";

sub init {
	$status = GetOptions(
                "p=s" => \$community,"community=s" => \$community,
                "h=s" => \$hostname, "hostname=s" => \$hostname,
                "i=s" => \$item, "item" => \$item,
                );

	usage() if (!defined($community) || !defined($hostname) || !defined($item));
	main();
}

sub usage {
	print "Usage:\n";
	print "\t$0 -h <hostname> -p <community>  -i <item>\n";
	print "\tItem can be: ";
	print "'tray', 'toner', 'paper'\n";
	exit(3);
}


sub main {

	# veriry printer snmp
	system("$snmpget -Oq -v 1 -c $community $hostname .1.3.6.1.2.1.1.1.0 2>/dev/null 1>&2");
	if ($? != 0) {
		print "CRITICAL - Erro conectando snmp impressora remota $hostname\n";
		exit(2);
	}

        @run = `$snmpwalk -Oq -On -v 1 -c $community $hostname .1.3.6.1.2.1.43.16.5.1.2.1 2>/dev/null`;
	foreach (@run) {
        	m/^.1.3.6.1.2.1.43.16.5.1.2.1.\d+\s"(.*)".*$/;
		$msg .= "$1 ";
	}


	if ($item eq "tray") {
		
		if ($msg =~ m/.*Bandeja\s+\d+\s+ausente.*/) {
			print "CRITICAL - Bandeja_ausente\n";
			exit(2);
		}
        
	        if ($msg =~ m/.*Bandeja\s+\d+\s+vazia.*/) {
                        print "CRITICAL - Falta_papel\n";
                        exit(2);
                }

	} elsif ($item eq "toner") {

		if ($msg =~ /Fechar porta ou inserir/i) {
			print "CRITICAL - Tampa_aberta_ou_sem_toner\n";
			exit(2);
		}

	} elsif ($item eq "paper") {

		if ($msg =~ /atolamento/i) {
			print "CRITICAL - Papel_enroscado\n";
			exit(2);
		}

	} else {
		&usage();
	}

	print "0K - $msg\n";
	exit(0);

}

init();
