#!/usr/bin/perl
#
# Log file Tool for sending Operations critical events to Cloud Event Management
#
# The tool processes a file in a specific format... The file is created by any tool that examines logs and reports instances of known issues
#
# Contents of /tmp/loggingErrors.txt
#


use Time::HiRes;
my $start_time = [Time::HiRes::gettimeofday()];
`clear`;

# Check for Lock File - Exit if present
my $LockFile = "/tmp/CEMLogMon.lck";
if (-e $LockFile) 
{
  print "\nLock File is present, the tools is currently running, exiting this invocation now!\n";
  exit;
}

# Set the Lock
`echo "Set Lock" > $LockFile`;

$mtime=`date "+%m%d%Y%H%M%S%Z"`;
$mtime =~ s/^\s+|\s+$//g;
$curlLog = "/tmp/CEMLogMonCurl.log";
`echo "Curl log for CEMLogMon.pl at $mtime" > $curlLog`;

# Globals
# Read the CEMLogMon Stats File
my $CEMOpsStats = "/tmp/CEMLogMonStats.txt";

# get Status File into @stats
use Tie::File;
tie my @stats, 'Tie::File', $CEMOpsStats;

# Read the Operations Teams file
my $OperationsLog = "/tmp/loggingErrors.txt";

# get Operations Teams file into @lines
open my $handle, '<', $OperationsLog;
chomp(my @lines = <$handle>);
close $handle;

# Interate over OPS TEAM file
foreach my $eachline (@lines)
{
  my ($key, $message, $source, $count, $delta) = split /:/, $eachline;
  $key =~ s/^\s+|\s+$//g;
  $message =~ s/^\s+|\s+$//g;
  $source =~ s/^\s+|\s+$//g;
  $count =~ s/^\s+|\s+$//g;
  $delta =~ s/^\s+|\s+$//g;
  my ($percent) = split /%/, $delta; 
  if ($key eq "Event") 
  {
     ###############################################################
     # All further processing done here as this is an Event: line 
     ###############################################################
     calcStats($key, $message, $source, $count, $percent);
  }
}

# Clear the lock before exit
`rm -f $LockFile`;

exit;

sub calcStats
{
    my $key = $_[0];
    my $msg = $_[1];
    my $src = $_[2];
    my $cnt = $_[3];
    my $perc = $_[4];
    print "$key $msg $src $cnt $perc\n";

    if (@stats == "")
    {  
       $saveline = "$msg : $src : $cnt";
       # Push the entry into the file and send an Event, the file is NEW but only if count > 0
       push @stats, $saveline;
       if ($cnt > 0)
       { 
        $msg = $msg . " first detected $cnt times!";
         sendEvent($msg, $src);
       }
    }
    else
    {
       # Process the file when found...
       my $notfound = 1;
       foreach my $es (@stats)
       {
           my ($filemsg, $filesrc, $filecnt) = split /:/, $es;
           $filemsg =~ s/^\s+|\s+$//g;
           $filesrc =~ s/^\s+|\s+$//g;
           $filecnt =~ s/^\s+|\s+$//g;
		   my $sendupdateevent = 0;
           if ($filemsg eq $msg && $filesrc eq $src)
           {
		      ## We Found the Entry - we must process it, update it and send an event if the delta is greater than the percentage 
              $notfound = 0; 
              #my $sendupdateevent = 0;
              if ($filecnt == 0 && $cnt > 0)
              {
                # upon first detection, always send an event 
                $sendupdateevent = 1;
                $es = "$msg : $src : $cnt";
				$msg = $msg . " first detected $cnt times!";
              }
			  if ($cnt > $filecnt && $filecnt > 0)
              {
                # We have new arrivals of this entry, so update it then test for % increase to decide if event is needed
                $es = "$msg : $src : $cnt";
				if (((($cnt-$filecnt)/$cnt)*100) > $perc)
                {
				  # The delta is greater than the specified percentage - we need to send an event
				  $delta = $cnt - $filecnt;
                  $msg = $msg . " detected $delta more times for a total of $cnt! ";
                  $sendupdateevent = 1;
                }
              }
           }
           if ($sendupdateevent)
           {
              sendEvent($msg, $src);
           }
        }
        if ($notfound)
         {
           ## We did not find the entry so its new... log the relevant data for next time
           $saveline = "$msg : $src : $cnt";
           # Push the entry into the file and send an event, the entry is NEW
           push @stats, $saveline;
           if ($cnt > 0)
           {
             $msg = $msg . " first detected $cnt times!";
             sendEvent($msg, $src);
           }
         }
    }
}

sub sendEvent
{
($smsg,$ssrc) = @_;

print "Sending Event with smsg='$smsg' and ssrc='$ssrc'\n";

system("./CEMSendEvent.sh -m '$smsg' -s '$ssrc' -r false");

}

