#!/usr/bin/env perl

use Nagios::Plugin;
use DBI;

my $PROGNAME = 'PSQL_QUERY';
my $VERSION  = '0.9';

my $np = Nagios::Plugin->new(
	usage => "Usage: %s [ -H <host> ] "
		. "-d <database> -u <username> [ -p <password ]"
		. " [ -c|--critical=<threshold> ] [ -w|--warning=<threshold ] -q <query>",
	version	=> $VERSION,
	plugin 	=> $PROGNAME,
	shortname => uc $PROGNAME,
	blurb 	=> 'Postgresql query result checking',
	extra	=> "\n\nCopyright (c) 2010 Sergey Zasenko",
);

$np->add_arg(
	spec => 'host|H=s',
	help => '-H, --host=hostname or ip address of pg server',
	required => 0,
);

$np->add_arg(
	spec => 'database|d=s',
	help => '-d, --database=database to use.',
	required => 1,
);

$np->add_arg(
	spec => 'user|u=s',
	help => '-u, --user=connect to the database as the user',
	required => 1,
);


$np->add_arg(
	spec => 'password|p=s',
	help => '-p, --passoword=password for user',
	required => 0,
);

$np->add_arg(
	spec => 'query|q=s',
	help => '-q, --query=query to execute',
	required => 1,
);

$np->add_arg(
	spec => 'warning|w=s',
	help => '-w, --warning=THRESHOLD. See '
	. 'http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT '
	. 'for the threshold format',
);

$np->add_arg(
	spec => 'critical|c=s',
	help => '-c, --critical=THRESHOLD'
);

$np->getopts;

$np->set_thresholds( critical => $np->opts->critical, warning => $np->opts->warning );

my $output = 'Unknown error';
my $result = 'UNKNOWN';

eval {
	my $source = 'dbi:Pg:database=' . $np->opts->database;
	if ( $np->opts->host ) {
		$source .= ';host=' . $np->opts->host;
	}

	my $db = DBI->connect(
		$source,
		$np->opts->user, $np->opts->password,
		{ ReadOnly => 1, RaiseError => 1, AutoCommit => 0 }
	);

	my $sth = $db->prepare( $np->opts->query );
	$sth->execute;

	my ( $qresult ) = $sth->fetchrow_array;

	$sth->finish;
	$db->disconnect;

	$np->add_perfdata(
		label 	=> 'result',
		value 	=> $qresult,
		warning => $np->opts->warning,
		critical => $np->opts->critical,
	);

	$result = $np->check_threshold( check => $qresult );
	$output = $np->opts->query . " => $qresult";
};

if ($@) {
	$output = $@;
	$result = 'CRITICAL';
}
$np->nagios_exit( $result, $output );

	
