#!/usr/bin/perl

use strict;
use NOCpulse::Config;
my $np_cfg = new NOCpulse::Config;

  # Logs
  my $log_dir  = $np_cfg->get('notification','log_dir');
  my $log_file = "$log_dir/notif-escalator.log";

  my $key_name=$ARGV[0];
  my $WARNING_QUEUE_SIZE  = $ARGV[1];
  my $CRITICAL_QUEUE_SIZE = $ARGV[2];

  unless ($key_name && $WARNING_QUEUE_SIZE && $CRITICAL_QUEUE_SIZE) {
    &help;
    exit(1);
  }

  my $OK_EXIT = 0;
  my $WARNING_EXIT  = 1;
  my $CRITICAL_EXIT = 2;
  my $UNKNOWN_EXIT  = 3;
  my $exit_value=$OK_EXIT;

  my $queue_size;

# Open log for reading next record
  bailout ("Unable to open log $log_file for reading") unless(-r $log_file);
  open(FILE,"tail -f $log_file |");
  while (<FILE>) {
    if (/Sends\:.*Alerts\:.*VSZ\:/) {
#      print $_;
      /$key_name\:.(\d+)/;
      $queue_size = $1; 
      last;
    }
  }

  # output data for time series and setup exit status
  print "<perldata>\n<hash>\n";
  print '<item key="data">';
  print $queue_size;
  print "</item>\n</hash>\n</perldata>";

  if ($queue_size >= $CRITICAL_QUEUE_SIZE) {
    $exit_value=$CRITICAL_EXIT;
  } elsif ($queue_size >= $WARNING_QUEUE_SIZE) {
    $exit_value=$WARNING_EXIT;
  }
  exit $exit_value;

sub bailout {
  print STDERR "@_\n";
  exit($UNKNOWN_EXIT);
}

sub help {
  print "$0 [(Alerts|Sends)] [warning level] [critical level]\n";
  print "This script is meant for use with the Command Center remote program check with data.  It shows the number of alerts or sends currently in progress by the escalator.\n"
}
