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

#  $Name:  $ 
#  $Id: SSRR.pm,v 1.5 2004/10/15 18:49:06 ccadieux Exp $

use PDM;
use Date::Format;
use PDM::ConfigFile;
use SAF;
use Carp;
use Message;
use Util;
use System;
use strict;
use Util::Http;
use Snapshot;

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

sub description {'SSRR'}

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

  my($p) = { pdm => $pdm };

  bless($p,'Provider::SSRR');
  return $p;
}

use vars qw($S2S $SAVE_SSRR);

$S2S = "/var/remote.support/scripts/sendtosupport";

sub UPDATE {
  my($class, $q) = @_;
  my($active, $ip, $to, $err, $info);
  my $deny = Roles->verifyRole($q, "admin");
  my($renv, $dev, $host,$notifs) = PDM::ConfigFile->read;
  my $G = Labels->read();
  my $L = Labels->read('Provider')->section('ssrr');

  if ($q->{ACTION_update}) {
    if ($q->{proxy} && !Util->ping($q->{proxy}, 5)) {
      $err = Html->error($L->expand(bad_proxy=> 5) ); 
    } else {
      my $old = $renv->{'pro.ssrr.active'};
      $renv->{'pro.ssrr.active'} = $q->{active}? "Y":"N";
      $renv->{'pro.ssrr.frequency'}  = ($q->{freq} + 0) || 23;
      $err = Html->info($L->{err_1}); 
      if ($renv->{'pro.ssrr.active'} eq "Y"){
         # Must check to make sure activating is okay
	 if(opendir(DIR, "/var/remote.support/scripts")){
	   # package directory exists
	   closedir(DIR);
	   #Check to see if myname is set

	   open(O, "/etc/uucp/Permissions");
           my @l = <O>; close(O);
           my $l = "@l";
           $l =~ /MYNAME=(.*) MACHINE=/;
           my $machine = $1;
           if ($machine) {
	   
              if($old ne "Y") {
                 system("/bin/rm /var/opt/SUNWstade/DATA/OLD_REPORTS/*");
	      }
              if (open(O, "/var/remote.support/files/rss_params")) {
                 my($l, %H);
                 while ($l = <O>) {
                    if ($l =~ /([^\s]+)=(.*)/) {
                       my $name = $1;
                       my $val  = $2;
                       $val     =~ s/"//g;
                       $H{$name}   = $val;
                    }
                 }
                 close(O);
                 $renv->{customer}      = $H{CUSTOMER_NAME};
                 $renv->{site_name}     = $H{SYSTEM_NAME};
                 $renv->{cust_no}       = $H{SYSTEM_ID}           if ($H{SYSTEM_ID});
                 $renv->{site_city}     = $H{SYSTEM_CITY};
                 $renv->{site_state}    = $H{SYSTEM_STATE};
                 $renv->{site_zip}      = $H{SYSTEM_ZIP}          if ($H{SYSTEM_ZIP});
                 $renv->{site_address}  = $H{SYSTEM_ADDRESS}      if ($H{SYSTEM_ADDRESS});
                 $renv->{site_country}  = $H{SYSTEM_COUNTRY}      if ($H{SYSTEM_COUNTRY});
                 $renv->{site_contact}  = $H{CUSTOMER_CONTACT}    if ($H{CUSTOMER_CONTACT});
                 $renv->{site_email}    = $H{CUSTOMER_EMAIL}      if ($H{CUSTOMER_EMAIL});
                 $renv->{site_contact_phone} = $H{CUSTOMER_PHONE} if ($H{CUSTOMER_PHONE});

              }
	   }else{
	     # Couldn't find machine name
	     $renv->{'pro.ssrr.active'} = "N";
	     $err = Html->error($L->{no_machine}); 

	   }

	 }else{
	   # Package directory doesn't exist
	   $renv->{'pro.ssrr.active'} = "N";
	   $err = Html->error($L->{no_directory}); 

	 }  
      }#else{
         # Active = NO
	 # No Checks need to be done
      #}
      PDM::ConfigFile->write( $renv, $dev, $host,$notifs);
    }
  }

  if ($renv->{'pro.ssrr.active'} eq "Y") {
    $active = "checked" ;
  } else {
    $info = "<font color=red><b>$G->{inactive}</b>";
  }
  my $freq = $renv->{'pro.ssrr.frequency'};
  my $proxy_ip = $renv->{'pro.ssrr.proxy'};

  #my $proxy = "<select name=proxy><option value=\"\">*$G->{local}";
  #foreach my $h (@$host) {
  #  my $ck = $h->{hostname} eq $renv->{'pro.ssrr.proxy'} ? "selected":"";
  #  $proxy .= "<option $ck>$h->{hostname}";
  #}
  #$proxy .= "</select>";

  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}, labelWidth => "40%"},
      [
       [f => $L->{active},    "<input type=checkbox name=active $active> $info" ],
       [f => $L->{heartbeat}, "<input type=text name=freq value=\"$freq\" size=2 maxlength=2>" ],
      ]);
  
  if (!$deny) {
    $scr->button2([
       [ l => 'ACTION_update' , $G->{submit_update} ],
     ]);
  }
  $scr->add("</form>");
  return $scr->out();

}
#<tr><td bgcolor=$Style::LIGHT width=20% align=right>$L->{proxy}:</td>
#      <td><input type=text name=proxy value=\"$proxy_ip\" size=30>


sub RUN {
  my($pro, $idList) = @_;
  my($f, $transmit);
  $DB::single = 1;

  my($renv, $devices, $hosts, $notifs) = PDM::ConfigFile->read();
  my $proxy;  # $renv->{'pro.ssrr.proxy'};

  if ($renv->{'pro.ssrr.active'} ne "Y") {
     Debug->print2("  not active, skipping.");
     return;
  }

  $DB::single = 1;
  open(O, "/etc/uucp/Permissions");
  my @l = <O>; close(O);
  my $l = "@l";
  $l =~ /MYNAME=(.*) MACHINE=/;
  my $machine = $1;

  if (!$machine) {
     Debug->err(SSRR => "Cannot find Machine name in Permissions file: You may not have installed SUNWrsssp or run update_rss_console ");
     $machine = $renv->{hostname};
  }

  if (!-x $S2S) {
    Debug->err(SSRR => "Cannot execute $S2S");
    return;
  }

  my $freq = $renv->{'pro.ssrr.frequency'} || 23;
  my($uucp) = "/usr/spool/uucppublic/rasagent" ;  # prefix

  my $uucpE = "$uucp.events";
  my $uucpB = "$uucp.beep";
  my $uucpN = "$uucp.nobeep";

  my($beeps , $beep_count , $nobeeps , $nobeep_count, $events, $event_count);

  my $edocs     = PDM->getMessagesFromList($idList);
  foreach my $ed (@$edocs) {
     next if ($ed->type() eq Message::TYPE_ALERT);
     next if ($ed->id("active") eq "N");

     my $ev         = $ed->instances()->[0];
     my $parent     = $ev->value("Parent");

     $events .= $ed->toC();

     next if ($ev->value("MgmtLevel") eq "DS");
     next if ($parent);

     $event_count++;

     Debug->print2("SSRR: " . $ed->className . " " . $ed->description );

     my $event_type = $ev->value("EventType");
     my $actionable = $ev->value("Actionable");
     my $sev        = $ev->value("Severity");
     $sev = int($sev + 0.5);

     if ($actionable eq "TRUE") {
        $beeps .= &short_format($ed, $sev, "Actionable", $renv);
        $beep_count++;

     } else {
       $nobeeps .= &short_format($ed, $sev, "Not-Actionable", $renv);
       $nobeep_count++;
     }
  }
  if ($event_count) {
     Timer->resetTimer("RSS");

  } elsif (Timer->getTimer("RSS") > $freq * 60) {
     Timer->resetTimer("RSS");
     $nobeeps .= &heartbeat($renv, $freq);
     my $ed = Health::Host->heartbeat("SSRR");
     $events .= $ed->toC();
     $nobeep_count++;
  }

  Snapshot->appendFile("SSRR", "BEEP   ------------------\n$beeps")   if ($beeps);
  Snapshot->appendFile("SSRR", "NOBEEP ------------------\n$nobeeps") if ($nobeeps);
  
  if ($event_count > 0) {
    &send_events($event_count, \$events, $proxy, $uucpE, "notify $machine nobeep");
  }

  if ($beep_count > 0) {
    &send_events($beep_count, \$beeps, $proxy, $uucpB, "notify $machine beep");
  }

  if ($nobeep_count > 0) {
    &send_events($nobeep_count, \$nobeeps, $proxy, $uucpN, "notify $machine nobeep");
  }

  Debug->print2("RSS done.");

# sendtosupport <filename> notify dsp1 beep
# sendtosupport <filename> notify dsp1 nobeep
# sendtosupport <filename> misc   dsp1 nobeep
# sendtosupport <filename> errfile   dsp1 nobeep  maybe to send rassagent log...

}

sub send_events {
  my($head, $events, $proxy, $fname, $opt) = @_;
  Debug->print2("Sending " . length($$events) . " bytes to $proxy:$fname");

  if ($proxy) {
    my $url = "Provider::SSRR::rss&opt=$opt&fname=$fname";
    my ($err, $rc) = Util::Http->postCommand($proxy, $url, &getHeader($head) . $$events, 20);

    Debug->err("RSS error: $err on $proxy:$fname ") if ($err);

  } else {
    if (!open(WE, ">$fname")) {
       Debug->err(SSRR => "Cannot open $fname: $!");
       return;
    }
    print WE &getHeader($head);
    print WE $$events;
    close(WE);
    chmod 0666, $fname;
    system("$S2S " . &short($fname) . " " . $opt);
  }
}

#
# proxy not supported anymore, ichabod handles it.
#
sub get_rss {
  my($q, $post_data) = @_;

  my $fname = $q->{fname};
  
  if (!open(WE, ">$fname")) {
     print "ERR Cannot open $fname: $!";
     return;
  }
  print WE $post_data;
  close(WE);
  chmod 0666, $fname;
  system("$S2S " . &short($fname) . " " . $q->{opt});
  print "OK\n";
  
}

sub short {
  my($f) = @_;
  my $ix = rindex($f, "/");
  return substr($f,$ix+1);
}

sub short_format {
  my($ed, $sev, $actionable, $renv) = @_;

  my %MAP = (0 => 'Normal',1 => 'Warning', 2 => 'Error', 3 => 'Down');
  my $cat     = $ed->id("category");
  my $agg_list= $ed->id("agg_list");
  my $ev      = $ed->instances()->[0];
  my $agent   = $ed->instances()->[1];
  my $solid;
  if ($ev->value("MgmtLevel") eq "DS") {
     $solid = $ev->value("SolutionId");
     my $ix = index($solid, ".");
     $solid = substr($solid,0, $ix) if ($ix > 0);
  }
  my $source  = $agent->propertyByName('IdentificationCode')->value if ($agent);
  $sev = $MAP{$sev};
  my $etype   = $ev->value('EventType');
  my $g_no    = $ev->value("GridNo") ;
  my $g_code  = $ev->value("GridCode") ;
  my $dev_name= $ev->value("TargetName") ;
  my $caption = $ev->value("DisplayTopic") || $ev->value('Caption');
  my $dev_key = $ev->value("Target") ;
  my $etime   = $ed->eventTime();
  my $agg     = $ev->value("Aggregate");
  my $ed_desc = $ed->eventData("Description");
  my $ed_discl= $ed->eventData("Disclaimer");
  my($ix) = index($etype, '.');

  if ($ix > 0) {
    $cat   = substr($etype, 0, $ix);
    $etype = substr($etype, $ix+1);
  }

  my($data);
  if ($ed_desc =~ /:$/) {
      $data = $ev->value('Data');
      if ($data =~ /^#INSTRUMENTATION_REPORT/) {
        $data = "";
      } else {
        $data =~ s/ \|\| /\n /g;
      }
  }
  my $sev_txt = $Message::SEV_MAP{$sev} || $sev;
  my $out = "Category : " . uc($cat) . "$solid \n".
            "Site     : $renv->{site_name} $renv->{site_city} $renv->{site_state} \n".
            "Source   : $source \n"              .
            "Device   : $dev_name\n"              .
            "Severity : $sev_txt $actionable \n" .
            "EventType: $etype.$caption \n"               .
            "EventCode: $g_no \n"              .
            "EventTime: $etime \n"               . 
            "NsccUrl  : http://nscc.central:8080/cgi-bin/errors?GO=GUI::Grid::info&code=$g_code\n".
            "\n$ed_desc $ed_discl\n";

  $out .= "\n$data\n" if ($data);
  if ($agg > 1) {
     require EventDB;
     my($involved, $sub) = EventDB->sub_events($agg_list, 0, 1);
     $out .= $sub;
  }

  $out .= "-" x 70 . "\n";

  return $out;
}

sub heartbeat {
  my($renv, $freq) = @_;
  my $time = Util->get_today();
  my $out = "Category : heartbeat\n" .
            "Site     : $renv->{site_name} $renv->{site_city} $renv->{site_state} \n".
            "Source   : $renv->{hostname} \n" .
            "Frequency: $freq hours \n".
            "Severity : 0 \n".
            "EventTime: $time \n\n";

  return $out;

}



sub getHeader {
  my($cnt) = @_;

  my $today2 = ctime(time);
  my $today  = substr($today2,4,12);

  my $head =<<EOF;
RSS ERROR NOTIFICATION
Error Classification: RANDOM_ERRORS
Number of Occurrances: $cnt

   SYSTEM ERROR REPORT   Prepared on $today

Date $today2

EOF

  return $head;
}
  

  
1;
