#!/usr/bin/perl
# -----------------------------------------------------------------------------
#  check_ds_status : Nagios plugin for Stratus DS (Video Wall) check
# -----------------------------------------------------------------------------
#  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;

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

my $APL=$ENV{APL} || $np->nagios_exit( UNKNOWN, 'APL environment variable is not defined' );

use SKM::DB;
use Master::Conf;
use Node::Conf ":all";

$np->nagios_exit( OK, 'skipped on slave node' ) if ! am_I_master();

# Try connecting to db
my $dbh;
eval {
    $dbh = DBMaster({ PrintError=>0, RaiseError=>1, FetchHashKeyName=>'NAME_uc' });
};
$np->nagios_exit( CRITICAL, 'Database is DOWN' ) if $@;

my ($verbose_notes, $alert_notes, $critical_notes);

$np->nagios_exit( CRITICAL, "Video Wall[s] are in CRITICAL state\nCritical notes:\n${critical_notes}Warnings:$alert_notes" ) if $critical_notes;
$np->nagios_exit( WARNING, "Video Wall[s] warnings detected:\n$alert_notes" ) if $alert_notes;
$np->nagios_exit( OK, 'Video Wall[s] are running normally' );

# ---------------------------------------------------------------------------------

sub ds_status {
    my $ra;
    eval {
        $ra = $dbh->selectall_hashref(
            "select o.obj,o.name,a1.val as state, a2.val as status "
            ." from _objs o, _obj_attr a1, _obj_attr a2 "
            ." where otype='D' and subtype='V' and  o.obj=a1.obj and a1.attr='STATE'"
            ."   and o.obj=a2.obj and a2.attr='STATUS' and deleted=0",
            'OBJ',
            {Slice=>[]}
        );
    };
    $np->nagios_exit( CRITICAL, 'Can not read devices info from DB' ) if $@;
    
    my $disconnected=0;
    foreach my $obj( keys %$ra) {
        $disconnected++ if $ra->{$obj}->{STATUS} eq 'disconnected';
    }
    if($disconnected < 5) {
        foreach  my $obj( keys %$ra) {
            my $dev=$ra->{$obj};
            next unless $dev->{STATUS} eq 'disconnected';
            my $note=Encode::encode("utf8", "vMX Monitor #$obj ").$dev->{NAME}.Encode::encode("utf8", " is DISCONNECTED");
            $note = Encode::decode("utf8", $note);
            $alert_notes.="$note\n";
        }
    }elsif($disconnected) {
     $alert_notes.="System has $disconnected disconnected vMX Monitors\n";
    }
}

