#!/usr/bin/perl
# -----------------------------------------------------------------------------
#  check_osgi_status : Nagios plugin for checking OSGI runtime/bundles status
# -----------------------------------------------------------------------------
#  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' );
my $SMXCTL         ="sudo $APL/smix/bin/smxctl";

my (%status, $long_stat);
if (open STAT, "$SMXCTL extstatus 2>/dev/null |") {
    %status = map {/^(\w+)=(.*)$/} grep {/^\w+=/} <STAT>;
}
else {
    $np->nagios_exit( UNKNOWN, 'Can not obtain OSGI framework status' );
}

foreach my $k (keys %status) {
    $long_stat .= "$k=$status{$k}\n";
}

if (not defined $status{STATUS}) {
    $np->nagios_exit( UNKNOWN, 'OSGI framework status in UNKNOWN' );
}
elsif ($status{STATUS} ne 'run') {
    $np->nagios_exit( CRITICAL, 'OSGi Framework is not running' );
}
else {
    my $bundle_status = $status{BUNDLE_STATUS};
    if(!defined $bundle_status) {
        $np->nagios_exit( UNKNOWN, 'OSGI bundles status in UNKNOWN' );
    }

    if ($bundle_status ne 'ok') {
        $np->nagios_exit( CRITICAL, "OSGi bundles are in '$status{MESSAGE}' state" );
    }
}

$np->nagios_exit( OK, 'OSGi Framework is RUNNING, bundles are in NORMAL state' );