#!/usr/bin/perl 

## This program is written as a Remote Program with Data check.  It counts
## number of sends/alerts currently active on the notification server.

## Please see the following url for details on how to write your own check.
## https://command.nocpulse.com/help/userguides/user_guide_v2/Output/InfrastructureManagement.html#475254.

use strict;
use Getopt::Long;
use base 'Storable';
use NOCpulse::Config;
use NOCpulse::Notif::Escalator;
  
# Command Center remote program with data check required exit values.
  my $OK_EXIT = 0;
  my $WARNING_EXIT  = 1;
  my $CRITICAL_EXIT = 2;
  my $UNKNOWN_EXIT  = 3;
  my $exit_value=$OK_EXIT;
  
# Escalator file location
my $np_cfg = new NOCpulse::Config;
my $tmp_dir      = $np_cfg->get('notification','tmp_dir');
my $STATE_FILE   = "$tmp_dir/escalator.state";

# Program options from the command line
  my $debug = '';    # default value for debug is off
  my $show_sends;    # true if send count should be taken
  my $show_alerts;   # true if alert count should be taken
  my $warn;          
  my $crit;
  my $help;
  
# Get the command line options
  GetOptions ('help'           => \$help,
              'debug|verbose'  => \$debug, 
              'sends'          => \$show_sends,
              'alerts'         => \$show_alerts,
              'warning=i'      => \$warn,
              'critical=i'     => \$crit
             );

# Check to make sure the user provided enough of the options required
# to run the program.  If not pselfrint out the help section.
  unless (!$help && ($show_sends | $show_alerts) &&  $warn && $crit ) {
    &help();
    exit($UNKNOWN_EXIT)
  }

  my $escalator;
  eval {
    ($escalator) = Storable::retrieve($STATE_FILE);
  };
  if ($@) {
    exit($UNKNOWN_EXIT)
  }

  my $count;
  if ($show_sends) {
    $count = scalar(@{[ $escalator->_sends_keys ]});
  } else {
    $count = scalar(@{[ $escalator->_alerts_keys ]});
  }
 

# Print out the data in xml format required by a Command Center Remote Program
# with Data

  print "<perldata>\n<hash>\n";
  print '<item key="data">';
  print $count;
  print "</item>\n</hash>\n</perldata>";

# Check for threshold violations and set the appropriate program exit status

  if ($count >= $crit) {
    $exit_value=$CRITICAL_EXIT;
  } elsif ($count >= $warn) {
    $exit_value=$WARNING_EXIT;
  }
  exit $exit_value;

sub help {
  print "$0 [--help]  | ( [--debug] ( --sends | --alerts ) --warn=n --crit=n ) \n";
  print "-h, --help:                 display this help message\n";
  print "-d, --debug, -v, --verbose: turn on debug messages\n";
  print "--sends;                    count sends\n";
  print "--alerts;                   count alerts\n";
  print "-w, --warn, --warning:      number of occurences/minute as to cause a Command Center warning state change\n";
  print "--crit, --critical:         number of occurences/minute as to cause a Command Center critical state change\n";
}
