#!/usr/bin/perl
#
# Z39.50 plugin for Nagios.
#
# Ian Chard, University of Oxford
# <ian.chard@sers.ox.ac.uk>
#

use strict;

use lib '/usr/local/nagios/libexec';
use utils qw($TIMEOUT %ERRORS);
use Net::Z3950;
use Getopt::Long;


my ($verbose, $help, $host, $database, $query);
my $port=210;
my $warn=5;
my $crit=10;

Getopt::Long::Configure("no_ignore_case");
my $ok=GetOptions("v|verbose"	=> \$verbose,
		  "h|help"	=> \$help,
		  "w=i"		=> \$warn,
		  "c=i"		=> \$crit,
		  "H|hostname=s"=> \$host,
		  "p|port=i"	=> \$port,
		  "d|database=s"=> \$database,
		  "q|query=s"	=> \$query);


if(!$ok || $help)
{
	print "usage: $0 [-vhV] [-w warn] [-c crit] [-p port] -H host -d database -q query\n";
	exit $ERRORS{'UNKNOWN'};
}

if(!$host|| !$database || !$query)
{
	print "ERROR: host, database name and query must ALL be specified.\n";
	exit $ERRORS{'UNKNOWN'};
}


$SIG{ALRM}=\&timeout;

sub timeout
{
	print "CRITICAL: timed out after $TIMEOUT seconds\n";
	exit $ERRORS{'CRITICAL'};
}


my ($conn, $result);

my $now=time;
alarm $TIMEOUT;

if(!($conn=new Net::Z3950::Connection($host, $port)))
{
	print "CRITICAL: connection failed: $!\n";
	exit $ERRORS{'CRITICAL'};
}

$conn->option("databaseName", $database);

if(!($result=$conn->search("\@attr 1=4 $query")))
{
	print "CRITICAL: search failed: ".$conn->errmsg()." (".$conn->addinfo().")\n";
	exit $ERRORS{'CRITICAL'};
}

my $elapsed=time-$now;

my $status="OK";
$status="WARNING" if($elapsed>=$warn);
$status="CRITICAL" if($elapsed>=$crit);

print "$status: found ".$result->size()." records in $elapsed seconds\n";
exit $ERRORS{$status};
