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


#  $Id: SAE.pm,v 1.2 2004/12/06 22:10:32 ccadieux Exp $

use PDM;
use Carp;
use Message;
use Grid;
use Util;
use strict;
use TO;
use HBA;

#
#  T3 stand alone    : D
#  T3 in rack        : C
#  Rack from SP      : DS
#  Rack from outside : D
#


use base 'Provider';
sub revision {'$Revision: 1.2 $'}

sub new {
  my($self, $pdm)  = @_;

  my($p) = { pdm => $pdm };
  bless($p,'Provider::SAE');
  return $p;
}

sub description {"SAE"}

sub ISACTIVE {
  my($class, $renv) = @_;
  my $G = Labels->read();
  my $o = $renv->{'pro.sae.active'} eq "Y" ? "($G->{mode_on})" : "($G->{mode_off})";
  return $o;
}

sub UPDATE {
  my($class, $q) = @_;
  my($active, $ip, $proxy, $to, $err, $name, $nat, $info, $ip2);
  my($renv, $dev, $host,$notifs, $o);
  my $deny = Roles->verifyRole($q, "admin");
  my $G = Labels->read();
  my $L = Labels->read('Provider')->section('sae');

  if ($q->{ACTION_update}) {
    ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read;
    $renv->{'pro.sae.active'}     = $q->{active}? "Y":"N";
    $renv->{'pro.sae.ip'}         = $q->{ip};
    $renv->{'pro.sae.format'}     = 1;
    $renv->{'pro.sae.components'} = $q->{components} ? "Y" : "N";
    $renv->{'pro.sae.frequency'}  = ($q->{freq} +0) || 6;
    PDM::ConfigFile->write( $renv, $dev, $host,$notifs);
    $err .= Html->info($L->{update});
  }

  ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read();
  my($dh_active, $dh_info, $ck_active);

  if ($renv->{'pro.sae.active'} eq "Y") {
    $ck_active = "<input type=checkbox name=active checked>";
  } else {
    $ck_active = "<input type=checkbox name=active>";
    $info      = "<font color=red><b>$G->{inactive}</b>";
  }
  $ip      = $renv->{'pro.sae.ip'};
  my $freq = $renv->{'pro.sae.frequency'};
  my $ck1  = $renv->{'pro.sae.components'} eq "Y"? "checked" : "";

  my $scr = Html::Screen->new();
  $scr->add(" $err <form  method=get> <input type=hidden name=GO value=GUI::Providers::display>
              <input type=hidden name=option value=$q->{option}>");
  $scr->table({ title => $L->{label} },
    [
    [f => $G->{active},   "$ck_active $info"],
    [f => $L->{dev_ip},   "<input type=text name=ip value=\"$ip\" size=60>"],
    [f => $L->{heartbeat},"<input type=text name=freq value=\"$freq\" size=2 maxlength=2>&nbsp;$L->{minutes}"],
    ]);

  if (!$deny) {
     $scr->button2([
       [ l => 'ACTION_update' ,  $G->{submit_update} ],
      ]);
  }
  $scr->add("</form>");
  return $scr->out();

}
#      <tr><td bgcolor=$Style::LIGHT align=right>$L->{devEvents}:</td>
#        <td><input type=checkbox name=components $ck1>


sub RUN {
  my($pro, $idList) = @_;
  my($notifs, $notif, $p, $ed, $id, $admin, $eventType);

  my($pdm)   = $pro->{pdm};
  my($ed_desc, $email_text);
  my $edocs     = PDM->getMessagesFromList($idList);
  my($hostname) = System->hostname();

  my $L = Labels->read('Provider')->section('sae');
  my($renv, $devices, $hosts, $notifs) = PDM::ConfigFile->read();
  $DB::single = 1;

  my ($contract_count);

  my $contracts = Cache->read2("contracts");
  foreach my $c (keys %$contracts) {
    $contract_count++;
  }
  
  if ($renv->{'pro.sae.active'} ne "Y" && $contract_count == 0) {
     Debug->print2("  not active, skipping.");
     return;
  }

  my $format   = $renv->{'pro.sae.format'};
  my $compFlag = $renv->{'pro.sae.components'};

  my (@devEvents, %SAVE);
  # 
  my $DEVLIST = ",t3,6020,6120,dsp,";
  foreach $ed (@$edocs) {   # Each Message.
      next if ($ed->type() eq Message::TYPE_ALERT); # Skip alerts
      my $cat     = $ed->id("category"); # A5/T3 ...
      my $ev      = $ed->instances()->[0];
      my $mgmtLevel= $ev->value("MgmtLevel");
      if ($mgmtLevel eq "C" && index($DEVLIST, ",$cat,") >= 0) {
        my $target  = $ev->value("Target");
        push(@{$SAVE{$target}}, $ed);
      }
  }

  foreach $ed (@$edocs) {   # Each Message.
      next if ($ed->type() eq Message::TYPE_ALERT); # Skip alerts
      my $cat     = $ed->id("category"); # A5/T3 ...
      my $ev      = $ed->instances()->[0];
      my $agent   = $ed->instances()->[1];
      my $etype0  = $ev->value('EventType');
      my $sev     = $ev->value("Severity");
      my $target  = $ev->value("Target");
      my $agg     = $ev->value("Aggregate");
      next if ($agg);  # do not send aggregate events

      my $mgmtLevel= $ev->value("MgmtLevel");
      my $g_code  = $ev->value("GridCode");
      my $g_no    = $ev->value("GridNo");
      my $caption = $ev->value('Caption');
      my $component = $ev->value('Component');
      my $source  = $agent->value('IdentificationCode') if ($agent);

      my($g_info, $g_cause, $g_action) = 
                         Grid->getInfoString($etype0, $caption, $g_code);
      my $new = {};
      foreach $p (@{$ev->properties()} ) {
         my $n = $p->name();
         next if ($n eq "Data");
         $new->{$n} = $p->value();
      }
      $new->{category}   = $cat;
      $new->{source}     = $source;
      $new->{severity}   = $sev;
      $new->{grid_info}  = $g_info;
      $new->{grid_cause} = $g_cause;
      $new->{grid_action}= $g_action;
      $new->{grid_code}  = $g_no;
      $new->{renv_version}= $renv->{version};

      my($t1, $k1, $extra) = split(/\:/, $target);
      $target = "$t1:$k1";

      &addDelta($new, $target, $component);

      if ($mgmtLevel eq "C") {
         push(@devEvents,$new) if ($compFlag eq "Y");
      } else {
         push(@devEvents,$new);
      }
      if ($mgmtLevel eq "DS") {
         my $org = State->eventHash($ev->value("OriginalEvent"));
         my($org_cat, $rest) = split(/\./, $org->{EventType});
         if (index($DEVLIST, ",$org_cat,") >= 0) {
            my $org_target  = $org->{Target};
            my $org_caption = $org->{Caption};
            my $startID     = $ev->value('EventId');
            my $cnt = 2;
            foreach my $ed1 (@{$SAVE{$org_target}}) {
                my $ev1      = $ed1->instances()->[0];
                my $etype1   = $ev1->value('EventType');
                my $caption1 = $ev1->value('Caption');
                my $g_no1    = $ev1->value('GridNo');
                if ($caption1 ne $org_caption) {
                   my $new2 = {%$new};
                   $new2->{EventId} = "${startID}$cnt"; $cnt++;
                   $new2->{OriginalEvent} = 
                  "EventType="  . $ev1->value("EventType") .
                  "|Target="    . $ev1->value("Target") .
                  "|TargetName=". $ev1->value("TargetName") .
                  "|Caption="   . $ev1->value("Caption") .
                  "|Actionable=". $ev1->value("Actionable") .
                  "|SourceIP="  . $ev1->value("SourceIP") .
                  "|Severity="  . $ev1->value("Severity") .
                  "|PriorState="    . $ev1->value("PriorState") .
                  "|CurrentState="  . $ev1->value("CurrentState") .
                  "|CurrentValue="  . $ev1->value("CurrentValue") .
                  "|grid_code=$g_no1";
                   my $desc2 = $ev->value("Description");
                   my $ix = index($desc2, ":");
                   if ($ix > 0) {
                      $new2->{Description} = substr($desc2,0,$ix) . ": " .  $ev1->value("Description");
                   }
                   push(@devEvents, $new2);
                }
            }
         }
      }
         
  }
  
  if ($renv->{'pro.sae.active'} eq "Y") {
    &send(\@devEvents, $renv->{'pro.sae.ip'}, $format);
  }

  #
  # SEND TO EACH CONTRACT
  #
  foreach my $c0 (keys %$contracts) {
     my $contract = $contracts->{$c0};
     my $url      = $contract->{url};
     my @list;
     foreach my $e (@devEvents) {
       push(@list, $e) if ($e->{severity} >= $contract->{min_sev});
     }
     &send(\@list, $url, 0);
  }
}

sub addDelta {
  my($new, $target, $component) = @_;
  my $report = Report->readNew($target);
  my $old    = Report->readOld($target);
  if ($report) {
     if (!$old) {
       my $subreport = $report->subset($component);
       foreach my $k (sort keys %$subreport) {
          $new->{"InstrReport.$component.$k"} = $subreport->{$k};
       }
     } else {
       my $new_rep = $report->value();
       my $old_rep = $old->value();
       my (%SEND);
       foreach my $el (sort keys %$new_rep) {
          next if ($el eq "FC_COUNTERS");
          if ($new_rep->{$el} ne $old_rep->{$el}) {
             my $ix = rindex($el, ".");
             my $v = $ix > 0 ? substr($el, 0, $ix) : $el;
             $SEND{$v} = 1;
          }
       }
       foreach my $el (sort keys %$new_rep) {
          next if (index($el, "DiskPerf") > 0 || 
                   index($el, ".path0") > 0 || index($el, ".path1") > 0);
          my $ix = rindex($el, ".");
          my $v = $ix > 0 ? substr($el, 0, $ix) : $el;
          if ($SEND{$v}) {
            $new->{"InstrReport.$el"} = $new_rep->{$el};
          }
       }
     }
   } else {
     Debug->print2("SAE: no report for $target");
   }
}

# format=1: tab-delimited

sub send {
  my($events, $ip, $format) = @_;

  return if ($#$events < 0);
  return if (!$ip);
  my ($out, $x);
  for ($x=0; $x <= $#$events; $x++) {
     my $e = $events->[$x];
     $out .= "<event no=\"$x\">\n" if ($format != 1);
     foreach my $el (sort keys %$e) {
       if ($format  == 1) {
          my $v = $e->{$el}; $v =~ s/\n/ /g;
          $out .= "event.$x.$el\t$v\n";
       } else {
          $out .= "  <element name=\"$el\">$e->{$el}</element>\n";
       }
     }
     $out .= "</event>\n" if ($format != 1);
  }
  my $url =  ($ip =~ /^http/) ? $ip : "http://$ip";

  my $SAVE = System->get_home() . "/DATA/sae";
  
  my $date = Util->get_today();
  $date =~ s/ /_/g;
  open(O, ">>$SAVE/$date");
  print O $out;
  close(O);
  
  my($err, $resp) = Util::Http->post($url, $out, 20);
  if ($err) {
    Debug->print2("SAE_ERROR: $err");
  } else {
    Debug->print2("SAE_OK: $url : $resp");
  }
}
  
1;

