#!/usr/bin/perl -w

use strict;
use Getopt::Long;

my $verbose=0;
my $help;
my $hostname;
my $metric;
my $state;
my $debug;

my $TIMEOUT = 10;

GetOptions("help" => \$help,
           "host:s" => \$hostname,
           "metric:s" => \$metric,
           "state:s" => \$state,
           "debug" => \$debug,
           "verbose" => \$verbose );

my %ERRORS=(OK=>0,
            WARNING=>1,
            CRITICAL=>2,
            UNKNOWN=>3,
            DEPENDENT=>4);

my $ZGREP = "/usr/bin/zgrep";
my $SORT = "/bin/sort";
my $TAIL = "/usr/bin/tail";

my $result = $ERRORS{"UNKNOWN"};

# Just in case of problems, let's not hang Nagios
$SIG{'ALRM'} = sub {
     print ("ERROR: No response from $hostname (alarm timeout)\n");
     exit $ERRORS{"UNKNOWN"};
};

alarm($TIMEOUT);

##############################################################################
# output of ncm-ncd
#
my $timestamp = 'NOT FOUND';
my $errors    = 0;
my $warnings  = 0;

my $message;

my $cmd = "$ZGREP -h 'warnings executing configure' /var/log/ncm/ncd.log* | $SORT | $TAIL -1";

$_ = `$cmd`;

if (/^(.+)\s+\[\w+\]\s+(\d+) errors, (\d+) warnings executing configure$/) {
    $timestamp = $1;
    $errors    = $2;
    $warnings  = $3;

    if ( $errors > 0 ) {
        $message = "ERROR: $errors error(s)";
        $message .= ", $warnings warning(s)" if ( $warnings > 0 );
        $message .= " [$timestamp]";
        $result = $ERRORS{"CRITICAL"};
    }
    elsif ( $warnings > 0 ) { 
        $message = "WARNING: $warnings warning(s) [$timestamp]";
        $result = $ERRORS{"WARNING"};
    }
    else {
        $message = "OK: [$timestamp]";
        $result = $ERRORS{"OK"};
    }
}
else {
    $message = "UNKNOWN: could not determine result of last ncm-ncd run";
    $result = $ERRORS{"UNKNOWN"};
}

alarm(0);

print "$message\n";
exit($result);
