#!/usr/bin/perl -w
#
## check_lpc - nagios plugin 
##
## This plugin allows you to check the status of UNIX printers
## via the LPC command
##
## Copyright 2005 Emmett Hogan
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
#
#
use strict;
use English;
use Getopt::Long;
use File::stat;
use vars qw($printer_count $LPC $msg $exit_state);
use vars qw($timeout $verbose $warn $help $error_level $tag);
use vars qw(@prob_printers $current_printer);
use lib '/opt/nagios/libexec';
use utils qw (%ERRORS &print_revision &support);
#
#
sub print_help ();
sub print_usage ();


Getopt::Long::Configure('bundling');
GetOptions(
	"t"   => \$timeout,
        "v"   => \$verbose,
        "h"   => \$help,
        "g=s"   => \$tag,
        "w"   => \$warn);

if ($help) {
        print_help();
        exit $ERRORS{'OK'};
}

# Set timeout...
unless (defined $timeout) {
        $timeout = $utils::TIMEOUT ;      # default timeout
}
# Set timeout...
unless (defined $tag) {
        $tag = "LPC";      # default tag
}
#

# $warn means that we just want printer errors
# to be WARNINGS.
if (! $warn) {
        $error_level = 'CRITICAL';
} else {
        $error_level = 'WARNING';
}

$SIG{'ALRM'} = sub {
    print ("ERROR: timed out waiting for check.\n");
    exit $ERRORS{"WARNING"};
};
alarm($timeout);

$LPC = "/usr/sbin/lpc status all";

open(LPC, "$LPC|") || die "Couldn't run $LPC: $!.\n";

$current_printer = "none";
$printer_count = 0;

while (<LPC>) {
	chomp;
	if (/^(.*):$/) {
	    $current_printer = $1;
	    print "Checking $current_printer\n" if ($verbose);
	    $printer_count++;
	    next;
	}
	if (/disabled/i) {
		push(@prob_printers, $current_printer);
	}
	if (/waiting/i) {
		push(@prob_printers, $current_printer);
	}
	
}

if ($#prob_printers < 0) {
	$exit_state = 'OK';
	$msg = sprintf("%s OK - %d printer%s checked", $tag, $printer_count, ($printer_count == 1) ? "" : "s");
} else {
	$exit_state = $error_level;
	$msg = sprintf("%s %s - Faulted Printers: %s", $tag, $error_level, join(", ", @prob_printers));
}

print "$msg\n";
exit($ERRORS{$exit_state});


sub print_usage () {
        print "Usage:\n";
        print "  $0 [-w] [-v]\n";
}

sub print_help () {
        print_usage();
        print "\n";
	print "  -t  Plugin timeout in seconds (default = $utils::TIMEOUT)\n";
        print "  -w  Printer Errors are WARNINGS only.  (default = CRITICAL)\n";
        print "  -g  Message Line Tag. (default = LPC)\n";
        print "  -v  verbose mode\n";
        print "\n";
}

