#!/usr/bin/perl -w

use DBI;
use Getopt::Long;
use Nagios::Plugin;

use vars qw($opt_host $opt_user $opt_password $opt_database $opt_sql $PROGNAME $opt_help);
$PROGNAME = "check_firebird.pl";
use Nagios::Plugin::Functions qw(%ERRORS);
sub print_help();
sub print_usage();

$opt_help = "";
$opt_host = "";
$opt_sql = "SELECT FIRST 10 DISTINCT RDB\$RELATION_NAME FROM RDB\$RELATION_FIELDS WHERE RDB\$SYSTEM_FLAG=0";
Getopt::Long::Configure("bundling");
GetOptions
        ("H=s"  => \$opt_host, "host=s" => \$opt_host,
         "h"    => \$opt_help, "help"   => \$opt_help,
         "U=s"  => \$opt_user, "username=s"     => \$opt_user,
         "P=s"  => \$opt_password, "password=s" => \$opt_password,
         "D=s"  => \$opt_database, "database=s" => \$opt_database
);

sub print_help() {
        print "Created by Roman Kolasiewicz, Dec 2012
With this plugin you could check FirebirdSQL database status\n\n";
        print_usage();
}


if ( ($opt_help) || ( ($opt_help eq "") && ($opt_host eq "")) ) {
        print_help();
        exit $ERRORS{'UNKNOWN'};
}

if (($opt_database eq "") || ($opt_host eq "") || ($opt_user eq "") || ($opt_password eq "") ) {
	print "Not enough arguments - you need to specify hostname, username, password and database!\n\n";
	print_help();
	exit $ERRORS{'UNKNOWN'};
}

$dbh = DBI->connect("dbi:Firebird:db=". $opt_database .";host=". $opt_host, $opt_user, $opt_password);
 if (!$dbh) {
    exit $ERRORS{'CRITICAL'}
 };

$sql = $dbh->prepare($opt_sql);
if (!$sql) {
	print "CRITICAL: Database is not working properly: ". $DBI::errstr . "\n";
	exit $ERRORS{'CRITICAL'};
}
else {
	print "OK: Database looks intact\n";
	exit $ERRORS{'OK'};
}

sub print_usage () {
        print "Required arguments:
-H, --host=HOST\n\tdatabase host
-U, --username=USERNAME\n\tdatabase username
-P, --password=PASSWORD\n\tdatabase password
-D, --database=DATABASE\n\tpath or alias to database
Optional arguments:
-S, --sql=SQL\n\tsql query to run
-h, --help\n\tprint this message\n";
}
