#!/opt/OV/bin/Perl/bin/perl
#
# Check_NodeDownFile.ovpl object_ID [information]
#
# Check if a file: $OV_TMP/NodeDown_objectID.txt has been created previously.
# If present, a real OV_Node_Down has occured previously and now a real OV_Node_Up
# message should be displayed in the Alarm browser and the file has to be deleted to rearm
# the mechanism. The file contents and given information can be used as desired.
# (e.g. display nodename, calculate the downtime etc.)
# Also append info to the $OV_TMP/NodeDown.log file.

($wday,$y,$m,$d,$H,$M,$S)=(localtime(time))[6,5,4,3,2,1,0];
$tid=sprintf("%04d%02d%02d %02d:%02d:%02d",1900+$y,$m+1,$d,$H,$M,$S);
$a=time;
#`print "$a $tid Node UP  $ARGV[1] $ARGV[0]">>/var/opt/OV/tmp/Bastian.log`;

use OVvars;

$a=time;
$tidbefore=&hittaidtid($ARGV[0]);
$difftid=($a-$tidbefore)/60;
#$result=("%.3f", $difftid); 

($m,$d,$H,$M,$S)=(localtime($difftid))[4,3,2,1,0];
$lokaltid=sprintf("%02d%02d %02d:%02d:%02d",$m+1,$d,$H,$M,$S);
$lokaltid=sprintf("%02d:%02d:%02d",$m+1,$d,$H,$M,$S);

       my $infile = "/var/opt/OV/tmp/NodeDown_$ARGV[0].txt";
       my $outfile = '/var/opt/OV/tmp/downup.log';

       open(FILE, '<', $infile) or die "Unable to open $infile: $!";
       open (DOWNUP, '>>', $outfile ) or die "Cannot create/open $outfile: $!"; 
       
  while(<FILE>){

      next if /^$/;
      my ( $a1, $a2, $a3, $a4, $a7 ) = (split('\s+', $_))[1,2,3,4,7];
      print DOWNUP "\n$a1 $a2 $a3 $a4 $a7\n";
      print DOWNUP "$tid Node UP $ARGV[1] Downtime: \n";
      #printf DOWNUP "%d Node UP %s  Downtime: %d", $tid, $ARGV[1], $difftid;
}
close FILE;
close DOWNUP;
 
sub hittaidtid() {
      my ($id)= @_;
     open(FILE,"./NodeDown_$ARGV[0].txt");
      while(<FILE>) { 
          ($t,$d1,$d2,$d3,$d4,$d5,$i,$rest)=split(); 
          if ($i == $id) { 
            $ti=$t;
           } 
        }
        close(FILE);
        return $ti;
}

sub log {
  my ($logstring)= @_;

  open (LOGFILE, ">>$OV_TMP/NodeDown.log") ||
     die ("Cannot create/open $OV_TMP/NodeDown.log");
  print LOGFILE "$logstring\n";

  close LOGFILE;
}
if  ($#ARGV >= 0) {
  $objectID = $ARGV[0];
  $downfile = "$OV_TMP/NodeDown_$objectID.txt";
}
else {
  &log ("Check_NodeDownFile.ovpl called without parameters, can't check filename");
  exit 1;
}
open (DOWNFILE, "$downfile") || die ("Cannot open and check $downfile\n");
$contents = <DOWNFILE>;
if ($#ARGV >= 1) {
  $information = $ARGV[1];
  $message = $information;
}
else {
  $message = $contents;
}
$category = "Status Alarms";
$localhost = "Localhost";
$message = "Node UP event for Object ID $objectID $message";
&log ("$a $tid Node UP objectID $ARGV[0] $ARGV[1] Diff Tid: $difftid");
$cmd = "ovevent -c \"$category\" \"\"";
$cmd .= " .1.3.6.1.4.1.11.2.17.1.0.58916872";
$cmd .= " .1.3.6.1.4.1.11.2.17.2.1.0 Integer 14";
$cmd .= " .1.3.6.1.4.1.11.2.17.2.2.0 OctetString \"$localhost\"";
$cmd .= " .1.3.6.1.4.1.11.2.17.2.4.0 OctetString \"$message\"";
`$cmd`;
close DOWNFILE;
unlink "$downfile";
exit 0;