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


#  $Id: Email.pm,v 1.37 2002/11/04 00:18:40 ccadieux Exp $

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

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

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

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

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

sub RUN {
  my($pro) = @_;
  my($notifs, $notif, $p, $ed, $id, $cat, $sev, $admin, $eventType);
  my(%EMAILS) = (); my(%COUNT) = ();
  my($pdm)   = $pro->{pdm};
  my($ed_desc, $email_text);
  my($edocs) = $pdm->getMessages;
  my($hostname) = System->hostname();
  my(%OUT);
  my $L = Labels->read('Provider')->section('email');

  my($renv, $devices, $hosts, $notifs) = PDM::ConfigFile->read();
  my($acronym) = $renv->{GSV_ACRONYM};
  my $EMAIL_PER_EVENT = $renv->{email_per_event};   # hotmail

  my($version) = $renv->{version};
  my($mailer) = $renv->{mailer} || "/usr/bin/mail";
  $DB::single = 1;
  if (!-x $mailer) {
    $mailer = "/bin/mail";
    return if (!-x $mailer);
  }
  my($st_found);
  if (System->get_stFound()) {
     $st_found = "*** $L->{diag}: " . System->get_stFound() . "\n";
  }
  unlink System->get_home() . "/DATA/Email_max" if ($main::FORCE);
  my $MAX = Util->deserialize("Email_max") || {};
  my $max_email = $renv->{max_daily_email};

  foreach $notif (@$notifs) {  # Each notification.
     $admin = Util->rtrim($notif->{email});
     $eventType = Util->rtrim($notif->{event});  # discovery|stateChange|..
     next if (!$admin);
     my $L = Labels->read('Provider' )->section('email');

     $p = $notif->{priority};
     foreach $ed (@$edocs) {   # Each Message.
       next if ($ed->type() eq Message::TYPE_ALERT); # Skip alerts
       $cat = $ed->id("category"); # A5/T3 ...
       next if ($ed->id("active") eq "N"); # no email if quiesced
       my($ev)     = $ed->instances()->[0];
       $sev        = $ev->value("Severity");
       my $mgmtLevel  = $ev->value("MgmtLevel") ;
       my $solid;
       if ($mgmtLevel eq "DS") {
         $solid = $ev->value("SolutionId");
         my $ix = index($solid, ".");
         $solid = substr($solid,0, $ix) if ($ix > 0);
       }

       if ($notif->{email_type} eq "C") {
          next if ($mgmtLevel eq "C");  # skip rack component events.
       } else {
          next if ($mgmtLevel eq "DS"); # skip enclosure level events in rack
       }
       my($agent)  = $ed->instances()->[1];
       my($source) = $agent->value('IdentificationCode') if ($agent);
       my($etype0) = $ev->value('EventType');
       my($caption)= $ev->value('Caption');
       my $actionable  = $ev->value('Actionable');
       my $target =  $ev->value('Target');
       my $targetName =  $ev->value('TargetName') || $target;
       my $caption0 = $caption;
       if (substr($target,0,5) eq "host." && index($caption, ".lun.") >= 0) {
          $caption0 = "lun";
       } elsif (substr($caption0,0,2) eq "M." || 
           substr($caption0,0,2) eq "P." || 
           substr($caption0,0,2) eq "X.") {
          $caption0 = substr($caption0,2);
       }
       my $email_key = "$target.$caption0";
       my $last_email;
       if ($target && $max_email) {
         my $today = time / 60;
         if ( exists($MAX->{$email_key}{$admin}) ) {
            if ($today - $MAX->{$email_key}{$admin}[1] > (8 * 60)) {
               $MAX->{$email_key}{$admin}[0] = 0;
            } 
            if ($MAX->{$email_key}{$admin}[0] == $max_email) {
              $last_email = $L->expand("last_email", $target);
            }
            next if ( $MAX->{$email_key}{$admin}[0] > $max_email);
         }
         $MAX->{$email_key}{$admin}[1] = $today;
         $MAX->{$email_key}{$admin}[0]++;
       }
       my($etype)  = $etype0;
       my($ix) = index($etype0, '.');
       $renv->{language} = $notif->{language};
       my($g_info, $g_cause, $g_action, $g_code) =  Grid->getInfoString($etype0, $caption);
       my $gridInfo;
       if ($g_info) {
          $g_info =~ s/\n/\n /g;
          $gridInfo .= "\n$L->{info}:\n$g_info";
       }
       if ($g_cause) {
          $g_cause =~ s/\n/\n /g;
          $gridInfo .= "\n$L->{cause}:\n$g_cause";
       }
       if ($g_action) {
          $g_action =~ s/\n/\n /g;
          $gridInfo .= "\n$L->{action}:\n$g_action";
       }
       #$gridInfo =~ s/<td>/ /g;
       #$gridInfo =~ s/<[big\/trd]+>//g;
       #$gridInfo =~ s/<table[ tablecsingpdgor=\d]+>/ /g;

       if ($ix > 0) {
         $etype = substr($etype0, $ix+1);
         $cat   = substr($etype0, 0, $ix);
       }
       next if (($notif->{device} ne "*") && lc($notif->{device}) ne lc($cat) );
       next if (($eventType       ne "*") && index(lc($eventType),lc($etype)) < 0 );
       my $run = 0;
       if ($p eq "*") {
          $run = 1;
       } elsif ($p == 91 && $actionable eq "TRUE") {
          $run = 1;
       } elsif ($p == 9 && $sev >= 1) {
          $run = 1;
       } elsif ($p == $sev) {
          $run = 1;
       }
       next if (!$run);

       $ed_desc = $ed->eventData("Description");
       my($eid) = $ed->eventData('EventId');
       my($etime) = $ed->eventTime();
       my($data);
       if ($ed_desc =~ /:$/) {
            $data = $ev->value('Data');
            $data =~ s/ \|\| /\n /g;
       }
       my $sev_txt = $Message::SEV_MAP{$sev} || $sev;
       $sev_txt .= " (Actionable)" if ($actionable eq "TRUE");

       if ($notif->{script} && -x $notif->{script} ) {
          my $dd = $ed_desc; $dd =~ s/\"//g;
          my $tt = $target || $source;
          my $com = "$notif->{script} -C \"$cat\" -S $sev -T \"$tt\" -E \"$etype.$caption\"  -D \"$dd\"";
          Util->run_command($com, "command", 20);
       }

       my $ss = ($sev >= 2) ? "E": ($sev == 1? "W":"I");
       $OUT{"${admin}:$ss"}{type} = $notif->{type};

       my $content = 
                "$L->{site} $renv->{site_name} $renv->{site_city} $renv->{site_state} \n".
                "$L->{source} $source\n"         .
                "$L->{sev} $sev_txt \n"          .
                 $L->{cat} . " " . uc($cat) . "$solid\n" .
                "$L->{devid} $targetName [$target]\n"          .
                "$L->{type} $etype.$caption\n"   .
                "$L->{code} $g_code\n"           .
                "$L->{time} $etime\n$last_email\n"          .
                "$L->{descr}\n$ed_desc\n$gridInfo\n\n";
       $content .= "DETAILS:\n$data" if ($data);

       if ($EMAIL_PER_EVENT) {
          my $sub = "$hostname: $cat.$etype $ed_desc";

          Util->run_command("$mailer $admin", "mail", 10,
            {data => "From: Network Storage Agent\n".
                  "Subject: $sub\n\n" .
          $L->expand('requested', $hostname) .
          "\n$st_found\n" . $content });
          Debug->print2("Email $etype to $admin");

       } else {
          $OUT{"${admin}:$ss"}{desc}    .= $ed_desc;
          $OUT{"${admin}:$ss"}{content} .= $content;
          $OUT{"${admin}:$ss"}{content} .= "\n" . "-" x 70 . "\n";
       }
    }
  }
  Util->serialize("Email_max", $MAX);

  my %S = ( W => $L->{warn}, E => $L->{err}, I => $L->{not});

  if (!$EMAIL_PER_EVENT) {
    foreach my $admin0 (keys %OUT) {
      my $type = $OUT{$admin0}{type};
      my($admin, $ss) = split(/\:/, $admin0);
      my $sev_txt = $S{$ss};

      if ($type eq "Email") {
        Debug->print1("Emailing to $admin");
        Util->run_command("$mailer $admin", "mail", 30,
            {data => "From: $acronym Agent\n".
                     "To: $admin\n".
                     "Subject: $sev_txt from '$hostname' ($version)\n\n" .
            $L->expand('requested', $hostname) .
            "\n$st_found\n" . $OUT{$admin0}{content} });

      } elsif ($type eq "Pager") {
        Debug->print1("Paging $admin");
          my $email_text =<<EOF;
From: $hostname
Content-Type: text/plain; charset=us-ascii

$OUT{$admin0}{desc}
EOF
           Util->run_command("$mailer $admin", "mail", 30,
                 {data => substr($email_text, 0, 250) });
      }
    }
  }
}

  
1;
