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

#  $Id: EventLog.pm,v 1.32 2002/09/19 15:43:55 ccadieux Exp $

use strict;
use Modules;
use System;
use Util::Http;
use Html::Tabs;
use vars qw ($CATEGORY $EVENT);


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

  my $out = "<select name=category>
            <option value=\"\">$G->{all}</option>
            <option value=message.>$L->{message_e}</option>
            <option value=host.>$L->{host_e}</option>
            <option value=topo.>$L->{topo_e}</option>
            <option value=agent.>$L->{agent_e}</option>
            <option value=t3message.>$L->{t3mess_e}</option>";

   my $mods = Modules->load("Agent");
   my $sel;
   foreach my $ag0 (@$mods) {
       my $ag = lc($ag0);
       my $mod = "Agent::$ag0";
       if ($sel = $mod->isSelectable()) {
         $out .= "<option value=$ag.>$sel</option>\n";
       }
    }
    $out .= "</select>";
}

sub get_EVENTS {

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

  return "<select name=event>
            <option value=\"\">$G->{all}</option>
            <option value=.Communication>$L->{comm}</option>
            <option value=.DiscoveryEvent>$L->{disco}</option>
            <option value=.AlarmEvent>$L->{alarm}</option>
            <option value=.RemovalEvent>$L->{remove}</option>
            <option value=.DiagnosticTest>$L->{diag}</option>
            <option value=.TopologyEvent>$L->{topo}</option>
            <option value=.AuditEvent>$L->{audit}</option>
            <option value=.StateChangeEvent>$L->{state}</option>
            <option value=.Agent>$L->{agent}</option>
            <option value=.backup>$L->{backup}</option>
            <option value=.patch>$L->{patch}</option>
            <option value=.LinkEvent>$L->{link}</option>
            <option value=.LocationCh>$L->{location}</option>
            <option value=.Statistics>$L->{stats}</option>
          </select>";
}


sub list {
  my($q) = @_;

  my $hname = System->hostname;
  my $hid = System->hostid;
  my $ip  = System->local_ip;
  my ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read();

  print Html->body();
  print Html->header2("monitor.log.events");
  my $L = Labels->read('GUI::EventLog')->section('events');
  my $G = Labels->read();

  my $EVENT = get_EVENTS();
  $CATEGORY = &get_categories();
  my $o =<<EOF;
<center>
<table border=1 cellspacing=0 width=90% bgcolor=white cellpadding=1><tr>
  <td colspan=5>
<form>
  <input type=hidden name=GO value=GUI::EventLog::display>
  <table border=0 cellspacing=2 width=100% cellpadding=0>
   <tr><td bgcolor=$main'LIGHT>&nbsp;<b>$L->{category}</td>
       <td bgcolor=$main'LIGHT>&nbsp;<b>$L->{event}</td>
       <td bgcolor=$main'LIGHT>&nbsp;<b>$L->{filter1}</td>
       <td bgcolor=$main'LIGHT>&nbsp;<b>$L->{filter2}</td>
   <tr><td>$CATEGORY</td>

     <td>$EVENT </td>
     <td><input type=text name=filter1 size=20></td>
     <td><input type=text name=filter2 size=20></td>
  </table>
<tr><td colspan=5 bgcolor=#666699><b><font color=white>&nbsp;$L->{select}</td>
<tr bgcolor=$main'LIGHT>
    <th><center>$L->{select0}</td>
    <td ><center><b>$L->{name}</td>
    <td ><center><b>$L->{type}</td>
    <td ><center><b>$L->{id}</td>
    <td ><center><b>$L->{ip}</td>
<tr>
EOF
  $o .= "<tr>
          <td><center><input type=checkbox name=host_local checked></td>
          <td>$hname</td>
          <td>$G->{master}</td>
          <td>$hid</td>
          <td>$ip</td>
          ";

  my($x);
  my(@H);
  foreach my $h (@$host) {
     push(@H, "$h->{ip} | $h->{hostname} | $h->{hostid} | $h->{ipno}");
  }
  foreach my $h (sort @H) {
     my($h_ip, $h_hostname, $h_hostid, $h_ipno) = split(/ \| /, $h); 
     $o .= "<tr>
          <td><center><input type=checkbox name=host_$h_ip></td>
          <td>$h_hostname</td>
          <td>$G->{slave}</td>
          <td>$h_hostid</td>
          <td>$h_ipno</td>
         ";
  }
  $o .= "</table><b><input type=submit name=ACTION value=\"$L->{submit_search}\">";
  print $o;

}


sub alerts {
  my($q) = @_;

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

  my $hname = System->hostname;
  my $hid = System->hostid;
  my $ip  = System->local_ip;
  my ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read;
  my $head = Html->header2("monitor.log.alerts");
  print "\n";
  my $EVENT = get_EVENTS();
  my $o =<<EOF;

<body bgcolor=$main'BGCOLOR>
<center>
$head
<table border=1 cellspacing=0 cellpadding=1 width=90% bgcolor=white><tr><td colspan=5>
<form>
  <input type=hidden name=GO value=GUI::EventLog::display>
  <table border=0 cellspacing=2 width=100% cellpadding=0>
   <tr><td bgcolor=$main'LIGHT>&nbsp;<b>$L->{category} </td>
       <td bgcolor=$main'LIGHT>&nbsp;<b>$L->{event}</td>
       <td bgcolor=$main'LIGHT>&nbsp;<b>$L->{severity}</td>
   <tr><td>$CATEGORY</td>
     <td>$EVENT </td>
     <td><select name=sev>
            <option value=\"Sev:\">$L->{sev_all}</option>
            <option value=\"Sev:3\">$L->{sev_down}</option>
            <option value=\"Sev:2\">$L->{sev_crit}</option>
            <option value=\"Sev:1\">$L->{sev_alert}</option>
            <option value=\"Sev:0\">$L->{sev_caution}</option>
         </select>
  </table>
<tr><td colspan=5 bgcolor=#666699><b><font color=white>&nbsp;$L->{select}</td>
<tr bgcolor=$main'LIGHT>
    <th><center>$L->{select0}</td>
    <td ><center><b>$L->{name}</td>
    <td ><center><b>$L->{type}</td>
    <td ><center><b>$L->{id}</td>
    <td ><center><b>$L->{ip}</td>
<tr>
EOF
  $o .= "<tr>
          <td><center><input type=checkbox name=host_local checked></td>
          <td>$hname</td>
          <td>$G->{master}</td>
          <td>$hid</td>
          <td>$ip</td>
          ";

  my($x);
  for ($x=0; $x <= $#$host; $x++) {
     my $h = $host->[$x];
     $o .= "<tr>
          <td><center><input type=checkbox name=host_$h->{ip}></td>
          <td>$h->{hostname}</td>
          <td>$G->{slave}</td>
          <td>$h->{hostid}</td>
          <td>$h->{ipno}</td>
         ";
  }
  $o .= "</table><b><input type=submit name=ACTION value=\"$L->{submit_search}\">";
  print $o;

}

sub info {
  my($q) = @_;
  require "Grid.pm";
  my $type = $q->{type};
  my $comp = $q->{comp};
  my $ev = Grid->getInfo($type, $comp);
  print "<body bgcolor=#E0E0E0>";
  print Html->header("EventGrid Info", "100%");

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

  my $actionable = ($ev->{actionable})? "Y":"N";
  my $im = Grid->get_sev_image($ev->{severity}) || "Information";

  my($cat, $rest) = split(/\./, $type, 2);
  my $pattern;
  if ($ev->{pattern}) {
    $pattern = " <tr><td align=right >$L->{pattern}:</td>
                <td colspan=3><b>$ev->{pattern}</td>";
  }
  my $desc = $ev->{desc} || "No description available!";
  my $type2 = $ev->{type} || $type;
  #$type2 =~ s/Event//;
  my $comp2 = $ev->{comp} || $comp;
  print "
  <table border=1 cellspacing=0 cellpadding=3 width=100% bgcolor=white>
    <tr><td align=right ><form>$L->{event}:</td><td><b>$type2
        <td align=right >$L->{sev}:</td><td>$im</td>
    <tr><td align=right >$L->{comp}:</td><td width=20%>&nbsp;<b>$comp2</td>
        <td align=right >$L->{actionable}:</td><td width=20%><b>$actionable</td>
    <tr bgcolor=#CCCCFF><td colspan=4><b>$L->{sample}</td>
    <tr><td bgcolor=white colspan=4>$desc</td>
   ";
  if (length($ev->{info}) > 1) {
     $ev->{info} =~ s/\n/<br>/g;
     print "<tr bgcolor=#CCCCFF><td colspan=4><b>&nbsp;$L->{info}</td>
           <tr bgcolor=white><td colspan=4>$ev->{info}</td>";
  }
  if (length($ev->{cause}) > 1) {
     $ev->{cause} =~ s/\n/<br>/g;
     print "<tr bgcolor=#CCCCFF><td colspan=4><b>&nbsp;$L->{cause}</td>
           <tr bgcolor=white><td colspan=4>$ev->{cause}</td>";
  }
  if (length($ev->{action}) > 1) {
     $ev->{action} =~ s/\n/<br>\n/g;
     print "<tr bgcolor=#CCCCFF><td colspan=4><b>&nbsp;$L->{action}</td>
           <tr bgcolor=white><td colspan=4>$ev->{action}</td>";
  }
  print "</table>";

}


sub display {
  my($q) = @_;
  my(@a, $cnt, $name);
  my($filter, $tab, $back);
  my $L = Labels->read("GUI::EventLog")->section("display");
  if ($q->{file}) {
     if ($q->{host}) {
       $q->{"host_" . $q->{host}} = 1;
     } else {
       $q->{host_local} = 1;
     }
     my($c1, $k1) = split(/\:/, $q->{file});
     $q->{filter1} = "Enc:$k1";
  }
  $filter  = "F1 $q->{filter1}, " if ($q->{filter1});
  $filter .= "F2 $q->{filter2}, " if ($q->{filter2});
  $filter .= "Cat $q->{category}, " if ($q->{category});
  $filter .= "Event $q->{event}, " if ($q->{event});
  print Html->body();

  if ($q->{sev}) {
    $filter .= ($q->{sev} eq "Sev:") ? "$L->{all}, ": "$q->{sev}, ";
    print Html->header2("monitor.log.alerts", undef,undef,undef, {noDoc => 1});
  } else {
    print Html->header2("monitor.log.events", undef,undef,undef, {noDoc => 1});
  }

  $filter = "All" if (!$filter);
  my($sev) = $q->{sev};
  $filter = substr($filter,0,-2) if (substr($filter,-2) eq ", ");

  $filter =~ s/\\//g;
  #if ($q->{sev}) {
  #   print Html->header2('monitor.log.display_alert');
  #} else {
  #   print Html->header2('monitor.log.display_event');
  #}
  #my($info1) = ($q->{sev}) ? "GUI::EventLog::alerts": "GUI::EventLog::list";

  #print "\n<body bgcolor=#F0F0F0 leftmargin=2 topmargin=2 marginwidth=2 marginheight=2>";
  my($back0, $t2);
  #if (!$q->{NOBACK}) {
  #  $t2 = $q->{sev} ? "AlertLog" : "EventLog";
  #  print Html->header($t2, "100%", "[ <a href=$Http::WEBPROC?GO=$info1>Back</a> ]", "Monitor.Log");
  #} else {
  #  print "
  # <table width=100% bgcolor=#666699 cellspacing=0 cellpadding=2 border=0><tr>
  #  <td><font color=white>&nbsp;<b>$t2 $filter</td>
  #  <td align=right><font color=white><b>&nbsp;$back0
  # </td></table></center>";
  #}

  my($lastfile) = System->get_home() . "/DATA/LastAlerts";
#  print "<table border=0><tr><td></table>";

  if ($q->{option})  {
     &sev_header($q, $lastfile);
     &sev_display($q->{option}, $lastfile);
     return;
  }

  open(AL, ">$lastfile");

  foreach my $host0 (keys %$q) {
    next if (substr($host0,0,5) ne "host_");
    my $host = substr($host0,5);

    if ($host eq "local" || $host eq System->hostname() ) {
      my $hname = System->hostname;
      print "<b>Local Host ($hname)</b>\n";
      $q->{GET} = undef;  # local 
      my($out) = &get_event_log($q);
      print AL $out . "\n";
    } else {

       my($fil) = "filter1=$q->{filter1}&filter2=$q->{filter2}&category=$q->{category}&event=$q->{event}&sev=$q->{sev}";
       $fil =~ s/ /+/g;
       print "Calling $host ...\n";

       my $page = Util::Http->getCommand($host, "GUI::EventLog::event_log&$fil", 30);
       print AL $page;
    }
  }
  close(AL);
  my (@SEV);

  if (!$sev) {
    if (open(AL, $lastfile)) {
      print "
      <script>
      function info(a,b) {
         var b = '$Http::WEBPROC?GO=GUI::EventLog::info&type=' + a + '&comp=' + b;
         var O = window.open(b,'linfo','menubar=yes,resizable=yes,scrollbars=yes,width=500,height=600');
         O.focus();
      }
      </script>
      <table border=1 cellspacing=0 cellpadding=1 width=100% bgcolor=white>
    <tr bgcolor=#CCCCFF>$L->{header}";
      my(@gifs) = ('al_ok3','al_alert3','al_crit3','al_down3');
      my ($l);
      while ($l = <AL>) {
        my @O = split(/\t/, $l);
        next if ($#O < 4);
        next if (substr($O[0],0,2) eq "--");
        my $act = substr($O[4],7) eq "TRUE" ? "Y" : "N";
        my $sev = substr($O[3],4);
        my $ev = $O[1];  $ev =~ s/ /','/;
        my $ev2 = $O[1]; 
        $ev2 =~ s/Communication/Comm-/;
        $ev2 =~ s/Event//;
        $ev2 =~ s/\./. /;
        my $url = "<a href=javascript:info('$ev')>$ev2</a>";
        my $sev = "<img src=/gif/" . $gifs[$sev] . ".gif alt=$sev>";
        print "<tr><td><small>$O[0]<td><center>$sev<td>$url<td><small>$O[2]\n";
      }
      print "</table>";
      close(AL);
    }
  } else {
     open(AL, $lastfile);
     @SEV = ();
     my($l);
     while ($l = <AL>) {
        if ($l =~ /Sev:(\d)/) {
           $SEV[$1]++;
        }
     }
     close(AL);
     open(AL2, ">$lastfile.count");
     print AL2 "$SEV[0]|$SEV[1]|$SEV[2]|$SEV[3]|$SEV[4]";
     close(AL2);

     &sev_header($q, $lastfile);
     &sev_display($q->{option}, $lastfile);
  }
  #print "Done\n";
}

sub sev_header {
  my($q, $lastfile) = @_;
  my ($al, $l);
  open(AL2, "$lastfile.count");
  $l = <AL2>; close(AL2);
  my @sev = split(/\|/, $l);
  $sev[0] += 0;
  $sev[1] += 0;
  $sev[2] += 0;
  $sev[3] += 0;
  $sev[4] += 0;
  close(AL2);
  my $L = Labels->read('GUI::EventLog')->section('events');
  
  my($tt) = ["4=<img src=/gif/al_down.gif border=0 align=$al>$L->{sev_down1} ($sev[3])",
             "3=<img src=/gif/al_crit.gif border=0 align=$al>$L->{sev_crit1} ($sev[2])",
             "2=<img src=/gif/al_alert.gif border=0 align=$al>$L->{sev_alert1} ($sev[1])",
             "1=<img src=/gif/al_ok.gif border=0 align=$al>$L->{sev_caution1} ($sev[0])",
            ];

  my $tab = Html::Tabs->create(list  =>  $tt,
                       url  => "$Http::WEBPROC?GO=GUI::EventLog::display&sev=$q->{sev}",
                     width  => "100%",
             selectedColor  => "white",
         selectedTextColor  => "blue",
           backgroundColor  => $main'LIGHT,
        backgroundTextColor => 'black',
                  selection => $q->{option}
               );
  print "<table border=0><tr><td></table>" . $tab;
}

sub sev_display {
  my($opt, $file) = @_;
  my($l);
  my(@gifs) = ('al_ok2','al_alert2','al_crit2','al_down2');
  $opt = $opt - 1;

  open(AL, $file);
  my $cnt = 0;
  print "<pre>";
  while ($l = <AL>) {
     next if ($l !~ /Sev:(\d)/);
     next if ($opt >= 0 && $opt != $1);
     if ($cnt++ < 50) {
        print "<img src=/gif/$gifs[$1].gif>$l";
     } else {
        print $l;
     }
  }
  close(AL);    
  #print "Done\n";
}


#
# always pulls local data
# will print if called by a $q->{GET}, else will return it.
#
sub get_event_log {
  my($q) = @_;
  my($out, @a, $file, $l);
  my $MAXSIZE = $q->{GET} ? 30000: 50000;
  my($grep) = System->get_home() . "/bin/rgrep";
  if ($q->{sev}) {  # alerts have a sev
    $file = System->get_home() . "/DATA/Alerts.log";
  } else {
    $file = System->get_home() . "/DATA/Events.log";
  }

  if ($q->{filter1} || $q->{filter2} || $q->{category} || $q->{event} ||
      $q->{sev}) {
     my($command);
     foreach my $c ('filter1','filter2','category','event','sev') {
        if ($q->{$c}) {
           if ($command) {
              $command .= "|$grep  -p \"$q->{$c}\" -i L";
           } else {
              $command = "$grep -p \"$q->{$c}\" -f $file -i L";
           }
        }
     }
     $file = "$command|";
     if (!open(O, $file)) {
        $out .= "ERR Cannot read $q->{file}: $!<br>";
        return;
     }
  } else {
    if (!open(O, $file)) {
      $out .= "ERR Cannot read $q->{file}: $!<br>";
      return;
    }
    my $fsize = (stat($file))[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") {
        $a[$#a] .= "    - " . substr($l,1) . "\n" if ($#a >= 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");
       push(@a, "$time\t$b[1] $b[2]\t$b[3]\t$b[4]\t$b[5]\t$b[6]\n");
     }
   }
   close(O);
   my $x;
   for ($x=$#a; $x >= 0; $x--) {
     $out .= $a[$x];
   }
   if ($q->{GET}) {
      print "$out";
   } else {
      return $out;
   }
}

1;

