#!/usr/bin/perl
# -----------------------------------------------------------------------------
#  check_db_status : Nagios plugin for DB status checks
# -----------------------------------------------------------------------------
#  Created by: Andriy Fomenko
#  Authors: Alex Titov, Alex Tsibulnik, Andriy Fomenko
#  QA by:
#  Copyright: videoNEXT Federal, Inc., 2015
# -----------------------------------------------------------------------------

use strict;
use warnings;

use Nagios::Plugin;
use Nagios::Plugin::Getopt;

use SKM::DB;
use Node::Conf "DB_Version";

my $np = Nagios::Plugin->new( usage => "Usage: %s [ -v|--verbose ]" );

$np->getopts;

my ($ret, $dbh, %DBVer);

# Try to connect to db
eval {
    $dbh = DBMaster({ PrintError=>0, RaiseError=>1, FetchHashKeyName=>'NAME_uc' });
    $dbh->selectall_arrayref("SELECT COUNT(1) FROM _objs");
};

if($@) { 
    $np->nagios_exit( CRITICAL, 'Database is DOWN' );
}

eval {
    %DBVer = ();
	for my $db ('confdb', 'transdb') {
	    my $arr = $dbh->selectrow_arrayref("select version,iteration from version_$db");
	    $DBVer{$db}{ver}  = $arr->[0];
	    $DBVer{$db}{iter} = $arr->[1];
	}
};

if($@) {
    $np->nagios_exit( CRITICAL, 'Can not read database version markers' );
}
    
my $need_update = 0;
my %DBVerBld = %{ &DB_Version };
for my $db ('confdb', 'transdb') {
    my $vercmp = $DBVerBld{$db}{ver} cmp $DBVer{$db}{ver};
    my $itercmp = $DBVerBld{$db}{iter} <=> $DBVer{$db}{iter};
    last if $vercmp == 0 and $itercmp == 0 or $vercmp > 0;
    if ($vercmp < 0)  { $need_update = 1; last; }
    if ($itercmp < 0) { $need_update = 1; last; }
}

if($need_update) { 
    $np->nagios_exit( WARNING, "System database version is higher than software version.\nPrevious version configuration backup recovery is recommended" );
}

$np->nagios_exit( OK, 'Database is running NORMALLY' );
