#!/usr/bin/perl -w
use lib "/nz/kit/share/perl";
use nz::SQL;
use strict;
use Getopt::Long;
my $dbname="";
my $dbuser="";
my $dbpass="";
my $debug;
my $status;
my $max_second=7200;
my $Con;
my $Dbh;
my $qresp;

sub DbConnect() {
    my ($KITDIR, $DATADIR);
    $DATADIR = "/nz/data.1.0";
    $KITDIR  = "/nz/kit";
    #
    # Initialize nz::SQL
    #
    nz::SQL::config(KITDIR => $KITDIR, DATADIR => $DATADIR);
    my $dbrunning = nz::SQL::is_running;
    if ($dbrunning == 0) {
       print "database not running! Please check\n";
       exit 9;
    }
}
#
# only alert if this blocking session has occured over seconds defined in global max_second
#
sub RunCheck() {
	my $sql="
	SELECT *
	FROM _v_querystatus A 
	where A.SUBMITTIME is not null
	and sqlext..seconds_between(current_timestamp,  A.SUBMITTIME) > $max_second
	";
        $qresp = nz::SQL::query($dbname, $sql) or die "Query $sql failed: ", nz::SQL::error(), "\n";
        my $count = $qresp->{nrows};
	if ($count > 0)
	{
		$status=1;
	}
	elsif ($count == 0)
	{
		$status=0;
	}
	else
	{
		$status=3;
	}

	# 0 OK
	# 1 WARNING
	# 2 CRITICAL
	# 3 UNKNOWN

	if ($count >= 0)
	{
		print "$count sessions over $max_second \n";
	}
	else
	{
		print "Error - Verify connectivity and access.\n";
	}

	return $status;
}

#main
{
        GetOptions ("d=s"   => \$dbname,      # string
                    "debug" => \$debug)   # flag
        or die("Error in command line arguments\n");
        if (length($dbname) == 0) {
                $dbname='system';
        }
	DbConnect();
	my $rtn=RunCheck();
	if ($rtn == 0)
	{
		print "Ok\n";
	}
	else
	{
		print "Error\n";
	}

	exit $rtn;
}
