#!/usr/bin/perl
# -----------------------------------------------------------------------------
#  check_avatar_status : Nagios plugin for Avatar 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;
use JSON;

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' );
my $AV_STATUS = "$APL/av/bin/avatar_status";

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);

avatar_status();

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

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

sub avatar_status
{
    my $json = `$AV_STATUS DETAILS=1 2>/dev/null`;
    if ($json) {
        my $status = eval { decode_json $json };
        if ($@) {
            $alert_notes="Cannot get avatar status\n";
        }
        else {
            my $offline=0;
            foreach my $obj (keys %$status) {
                $offline++ if $status->{$obj}{status} eq 'OFFLINE';
            }
            if(! $offline) {
            } elsif($offline<5) {
                foreach my $obj (keys %$status) {
                    next if $status->{$obj}{status} ne 'OFFLINE';
                    my $note = "Avatar #$obj '$status->{$obj}{name}' is OFFLINE";
                    $alert_notes.="$note\n";
                }
            } else {
                my $note="System has $offline offline Avatars";
                $alert_notes.="$note\n";
            }
        }
    }
}
