package Client::EventLog;
#<copyright>
# ----------------------------------------------------------
# Sun Proprietary/Confidential Code
# Copyright 2001, Sun Microsystems, Inc. All rights reserved.
# ----------------------------------------------------------
#</copyright>

use Client;
use Grid;
use strict;
use Modules;
use State;
use System;
use bytes;
use Data::Dumper;

sub getHosts {
  
  print Client->http_OK();
  print "<HOSTS>\n";
  my ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read();
  print "  <VALUE  ID=\"local\">$renv->{hostname}</VALUE> \n";
  foreach my $h (@$host) {
    print "  <VALUE ID=\"$h->{hostname}\">$h->{hostname}</VALUE> \n";
  }
  print "</HOSTS>\n";

}

sub getCategories {

  my $L = Labels->read("GUI::EventLog")->section("events");

  print Client->http_OK();
  print  "<CATEGORIES> \n";
  print  "  <VALUE ID=\"message\">" . $L->{message_e} . "</VALUE> \n";
  print  "  <VALUE ID=\"host\">" . $L->{host_e} . "</VALUE> \n";
  print  "  <VALUE ID=\"topo\">" . $L->{topo_e} . "</VALUE> \n";
  print  "  <VALUE ID=\"agent\">" . $L->{agent_e} . "</VALUE> \n";

  require Agent;
  my $mods = Agent->findSelectableAgents();
  foreach my $ag0 (@$mods) {
    my @A = split(/=/, $ag0);
    print "  <VALUE ID=\"$A[0]\">" . $A[1] . "</VALUE> \n";
  }
  print  "</CATEGORIES> \n";

}

sub getTopics {

  my $L = Labels->read('GUI::EventLog')->section('events');

  print Client->http_OK();
  print "<TOPICS>\n";
  print "   <VALUE ID=\"Communication\">$L->{comm}</VALUE>\n";
  print "   <VALUE ID=\"DiscoveryEvent\">$L->{disco}</VALUE>\n";
  print "   <VALUE ID=\"RemovalEvent\">$L->{remove}</VALUE>\n";
  print "   <VALUE ID=\"DiagnosticTest\">$L->{diag}</VALUE>\n";
  print "   <VALUE ID=\"TopologyEvent\">$L->{topo}</VALUE>\n";
  print "   <VALUE ID=\"AuditEvent\">$L->{audit}</VALUE>\n";
  print "   <VALUE ID=\"StateChangeEvent\">$L->{state}</VALUE>\n";
  print "   <VALUE ID=\"ValueChangeEvent\">$L->{valueChange}</VALUE>\n";
  print "   <VALUE ID=\"Agent\">$L->{agent}</VALUE>\n";
  print "   <VALUE ID=\"backup\">$L->{backup}</VALUE>\n";
  print "   <VALUE ID=\"patch\">$L->{patch}</VALUE>\n";
  print "   <VALUE ID=\"LinkEvent\">$L->{link}</VALUE>\n";
  print "   <VALUE ID=\"LocationCh\">$L->{location}</VALUE>\n";
  print "   <VALUE ID=\"Statistics\">$L->{stats}</VALUE>\n";
  print "</TOPICS>\n";
}

sub getSeverities {

  my $L = Labels->read('GUI::EventLog')->section('events');

  print Client->http_OK();
  print "<SEVERITIES> \n";
  print "   <VALUE ID=\"Sev:3\">$L->{sev_down}</VALUE>\n";
  print "   <VALUE ID=\"Sev:2\">$L->{sev_crit}</VALUE>\n";
  print "   <VALUE ID=\"Sev:1\">$L->{sev_alert}</VALUE>\n";
  print "   <VALUE ID=\"Sev:0\">$L->{sev_caution}</VALUE>\n";
  print "</SEVERITIES> \n";

}

sub getTypes {

  my $L = Labels->read('GUI::EventLog')->section('events');
  
  print Client->http_OK();
  print "<TYPES> \n";
  print "    <VALUE ID=\"mgmtLevel:C\">$L->{type_sys}</VALUE> \n";
  print "    <VALUE ID=\"mgmtLevel:D\">$L->{type_comp}</VALUE> \n";
  print "</TYPES> \n";

}

sub getGridInfo {
  print Client->http_OK();
  my($q) = @_;
  require "Grid.pm";
  my($type, $comp, $ev, $desc, $severity, $code, $title, $locale);
  my $renv = System->get_renv();
  require Advisor;

  $code = $q->{code};
  $type = $q->{type};
  $comp = $q->{comp};
  $locale = $q->{locale};

  $ev   = Grid->getInfo($type, $comp, {code => $code, locale => $locale});
  
  if ($ev) {
    my $action = Advisor->process($ev->{action}, "Grid", undef, $q);
    print "<GRIDINFO> \n";
    print "  <ACTIONABLE>$ev->{actionable}</ACTIONABLE> \n";
    print "  <DESC>" . Client->xmlEncode($ev->{desc}) . "</DESC> \n";
    print "  <INFO>" . Client->xmlEncode($ev->{info}) . "</INFO> \n";
    print "  <CODE>" . Client->xmlEncode($ev->{code}) . "</CODE> \n";
    print "  <CAUSE>" . Client->xmlEncode($ev->{cause}) . "</CAUSE> \n";
    print "  <ACTION>" . Client->xmlEncode($action) . "</ACTION> \n";
    print "</GRIDINFO> \n";
  } else {
    print "<GRIDINFO> \n";
    print "</GRIDINFO> \n";
  }
}

sub getEventLog { 

  my($q) = @_;
  my $EV = &get_event_log($q);
  my $renv = System->get_renv(); 
  my $dispAggr = $q->{AGGR} ? 1:0;

  my ($lines, $l, $y, $item);
 
  print Client->http_OK();
  print "<LOG> \n";

  for ($y=$#$EV; $y >= 0; $y--) {
     my $ev = $EV->[$y];
     $l = $ev->[0];
     next if ($l =~ /AggregatedEvent/);
     my $data = $ev->[1];
     my @O = split(/\t/, $l);
     next if ($#O < 4);
     next if (substr($O[0],0,2) eq "--");
     my $date = $O[0];
     my @T = split(/ /, $O[1]);
     my $topic = $T[1];
     my $pos = index($T[0], ".");
     my $type = substr($T[0], 0, $pos);
     my $eventType = substr($T[0], $pos + 1);
     my $desc = $O[2];

     # change the way to get the following values to reduce the dependence
     # on the format
     
     my ($sev, $act,  $enc, $host, $agg, $grid);

     foreach $item (@O) {
       if($item=~ m/^Sev:/) {
	 $sev = substr($item,4);
       } elsif($item=~ m/^Action:/) {
	 $act = substr($item,7);
       } elsif($item=~ m/^Enc:/) {
	 $enc = substr($item,4);
       } elsif($item=~ m/^AgentH:/) {
	 $host = substr($item, 7);
       } elsif($item=~ m/^Agg:/) {
	 $agg  = substr($item, 4);
       } elsif($item=~ m/^ECode:/) {
	 $grid = substr($item,6)
       } elsif($item=~ m/^Topic:/) {
	 my $xx = substr($item,6);
     $topic = $xx if ($xx);
       }
     }

#     my $sev = substr($O[3],4);
#     my $act = substr($O[4],7);
#     my $enc = substr($O[5],4);
#     my $host = substr($O[7], 7);
#     my $agg  = substr($O[8], 4);



     # don't know what it is for
     # it's to hide the components of aggregated events (bug 5088882)
     #
     # but sometime user wants to see those aggregated events (bug 6183880)
     # discussed with Todd, we let it be optional at event filter.

     if(!$dispAggr) {
       next if ($agg < 0);
     }

     my $aggrStr = $agg < 0 ? "Y" : "N";

#     my $grid = substr($O[9],6);
     #my $grid_no = Grid->getNo($grid);

     $host = $renv->{hostname} if ($host eq "local");
     #my $ix2 = index($host, ".");
     #$host = substr($host,0,$ix2) if ($ix2 > 0);
    
     if($q->{type}) {
       if($q->{type} eq "host") {
	 next if($type ne "host" && $type ne "agent");
       } else {
	 next if($q->{type} ne $type);
       }
     }

     next if($q->{key} && $q->{key} ne $enc);
    
#    xml encoding
     $desc = Client->xmlEncode($desc);
     $data = Client->xmlEncode($data);

     print <<EOF;
     <EVENT ID=\"\">
       <DATE>$date</DATE>
       <SEVERITY>$sev</SEVERITY>
       <ACTION>$act</ACTION>
       <DESC>$desc</DESC>
       <GRIDCODE>$grid</GRIDCODE>
       <TYPE>$type</TYPE>
       <EVENTTYPE>$eventType</EVENTTYPE>
       <EVENT>$eventType</EVENT>
       <KEY>$enc</KEY>
       <TOPIC>$topic</TOPIC>
       <DATA>$data</DATA>
       <HOST>$host</HOST>
       <AGGR>$aggrStr</AGGR>
     </EVENT>
EOF
   }

   print "</LOG>\n";
 
}

sub get_event_log {
  my($q) = @_;
  my($out, @EV, $file, $l);
  my $MAXSIZE = $q->{MAXSIZE} || 50000;
  my($grep) = System->get_home() . "/bin/rgrep";
  $file = System->get_home() . "/DATA/" . ($q->{SYSTEM} ? "EventsSys.log" : "Events.log");
  my $ofile = $file;

  if ($q->{ALERT}) {  # alerts have a sev
     $q->{action} = "Action:TRUE";
  }

  if ($q->{hostname}) {  # specific slave host
     $q->{agenth} = "AgentH:$q->{hostname}";
  }
  my $erase;
  if ($q->{filter1} || $q->{filter2} || $q->{category} || $q->{event} ||
      $q->{sev} || $q->{action} || $q->{agenth} || $q->{eventtype}) {
     my($command);
     foreach my $c ('filter1','category','event','sev', 'action', 'agenth',
                    'eventtype') {
        if ($q->{$c}) {
           if ($command) {
              $command .= "|$grep  -p \"$q->{$c}\" -i L";
           } else {
              my $P = "-P \"$q->{filterOR}\"" if ($q->{filterOR});
              $command = "$grep -p \"$q->{$c}\" $P -f $file -i L";
           }
        }
     }
     $ofile = "/tmp/_rasevents.$$";
     system("$command > $ofile");
     $erase = 1;
  }
  if (!open(O, $ofile)) {
      $out .= "ERR Cannot read $ofile: $!<br>";
      return;
  }
  my $fsize = (stat($ofile))[7];
  if ($fsize > $MAXSIZE) {
     seek(O, - $MAXSIZE, 2);
     $l = <O>;
  }

  my $time;
  while ($l = <O>) {
     chop($l);
     my(@b) = split(/\t/, $l);
     if (substr($l, 0, 1) eq "L") {
        $EV[$#EV][1] .= substr($l,1) . "\n" if ($#EV >= 0);
     } else {
       $time = $b[0];
       $time =~ /(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/;
#      next if (!$1);
       $time = "$1-$2-$3 $4:$5:$6";
#      next if (!$b[1]);
       # my $type = sprintf("%-25.25s", $b[1]);
#       push(@a, "$time  $type  $b[2] $b[3]\n");
       $EV[$#EV+1][0] =  "$time\t$b[1] $b[2]\t$b[3]\t$b[4]\t$b[5]\t$b[6]\t$b[7]\t$b[8]\t$b[9]\t$b[10]\t$b[11]";
     }
   }
   close(O);
   unlink $ofile if ($erase);

   return \@EV;
}



1;
