package Agent::T3MESSAGE;
#<copyright>
# ----------------------------------------------------------
# Sun Proprietary/Confidential Code
# Copyright 2001, Sun Microsystems, Inc. All rights reserved.
# ----------------------------------------------------------
#</copyright>
#  $Name:  $ 
#  $Id: T3MESSAGE.pm,v 1.5 2006/05/25 21:50:37 mckenney Exp $

use strict;
use State;
use PDM::Parse;
use Report;
use Agent;
use base 'Agent';
use Policies;
use RasThread;

sub isSelectable { 0 }
sub revision     { '$Revision: 1.5 $'}
sub type         { Report::CAT_T3MESSAGE }
sub diskTotal    { 9    }

use vars qw( $ERR %FOUND);

sub new {
  my($self) = Agent->new();

  bless ($self, 'Agent::T3MESSAGE');
  return $self;
}
use vars qw ($DONE);


sub RUN {
   my($agent, $static_list) = @_;
   my($err_lines, $warn_lines,  $out,$device, $connect_errs);
   my($report ,  $id, $lines, $log_err, $type);
   my( $wwn, $portWWN, $port2WWN);
   $DB::single = 1;
   my $type = uc($agent->type());
 
   my $processed_list = [];
  
   my $renv     = System->get_renv();
   my $logfile  = $renv->{t300logfile};
   my $warn_lines = [];
   my $ISP;
   $DONE = 1;
   Debug->print1("Executing agent T3MESSAGE");

   my @t3_logfiles = split(/\s+/, $logfile);  
   foreach my $logf (@t3_logfiles) {
     if ($logf && -r $logf) {
       ($log_err, $lines) = $agent->read_log_file($logf,'NEW');  
       Debug->err('CANNOT_READ', $logf) if ($log_err);
       $agent->find_alert($lines, $device, \$ISP, $warn_lines);
     }
   }
 
   my $D = System->get_home() . "/DATA/DataHost";
   opendir(DH, $D); 
   my @dh_files = readdir(DH); closedir(DH);
   foreach my $f (@dh_files) {
      next if ($f !~ /t3loglines$/);
      ($log_err, $lines) = $agent->read_log_file("$D/$f",'24','00');  
      $agent->find_alert($lines, $device, \$ISP, $warn_lines);
      unlink "$D/$f";
   }
      
   my($name) = $renv->{hostname} || System->hostname();
   if ($#$warn_lines >= 0) {
      $id = {
            deviceName  =>  ($renv->{solution} eq "N") ? $renv->{hostname}: System->hostid(),
            active      => "Y",
            logFile     => $logfile,
            display     => "$name (id=" . System->hostid() . ")",
            name        => $name, 
            class       => "host",
            category    => Report::CAT_T3MESSAGE,
            ip          => "",
         };
      $report->{"id.name"} = $name;
      my $new_rep = Report->new($id, $report , $warn_lines, Report::STATUS_DONT_SAVE);
      require Health::Message;
      my $broke_list = Health::Message->all_logic($new_rep);
      foreach my $dev (@$broke_list) {
         $dev->{problems} = 2; # broke but not processed yet.
         push(@$processed_list, $dev);
      }
      PDM->saveReport($new_rep);
   }
 
   return $processed_list;
}



############################################################
#                    SUBROUTINES
############################################################


# 1 = warning
# 2 = errors

sub find_alert {
  my($agent, $lines, $device, $ISP, $err) = @_;
  my( $level, $name, $no1, $no2, $rest);
  my($m, $year, $date, $comp, $x);
  my($ipno);

  my $renv   = System->get_renv();
  my $Config = PDM::ConfigFile->read();
  my $devs = $Config->devices();
  my ( %IP, %DEV);
  my $policies = Policies->new("array_policies");
  my $playback = $main::TESTMODE;

  my ($write, $comp1, $comp2, %MAP);
  #
# RE-START MONITORING
#
  foreach my $d (@$devs) {
      if ($d->{skip}) {
        my $age = (time - $d->{skip}) / 60;
        my $units = $d->{units} || 1;
        if ($age > $units * 60) {
           delete $d->{skip};
           $d->{active} = "Y";
           $write=1;
           Events->saveEvent("QE", $d->{type}, $d->{key}, "Monitoring of device $d->{name} re-started");
        }
      }
  }
  

  for ($x=1; $x <= 2; $x++) {
    foreach my $d (@$devs) {
       next if (!$d->{ipno});
       my $key = $d->{type} . ":" . $d->{key};
       my $hn  = $d->{host} || $renv->{hostname}; 

       if ($x == 1      && ($hn eq $renv->{hostname}) ) {
          $IP{$d->{ipno}} = $key;
          $DEV{$d->{ipno}} = $d;

       } elsif ($x == 2 && !exists $IP{$d->{ipno}}) {
          $IP{$d->{ipno}} = $key;
          $DEV{$d->{ipno}} = $d;
       }
       if ($x == 1 && $playback) {
         my $name    = $d->{name};
         $MAP{$name} = $d->{ipno};
         my $ix      = index($name, "-");
         if ($ix > 0) {
            $name       = substr($name, $ix+1);
            $MAP{$name} = $d->{ipno};
         }
       }
    }
  }


  for ($x = 0; $x <= $#$lines; $x++ ) {
     my $line = $lines->[$x];
     my(@a) = split(/\s+/, $line);
     if (substr($a[3],0,1) eq "[") {
       $a[3] = substr($a[3],1,-1);
       if ($a[3] =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)\.(\d+)/)  {
          $a[3] = "$1.$2.$3.$4";
       }
     }
     my $t3_ip = $MAP{$a[3]} || ($playback ? 0 : Util->name2ip($a[3])) || $a[3];
     $MAP{$a[3]} = $t3_ip if ($a[3] ne $t3_ip);

     my ($key, $knownT3, $key0);
        
     if (exists($IP{$t3_ip})) {
       $FOUND{$t3_ip}++;
       next if ($DEV{$t3_ip}{active} eq "N");
       next if (index("|$renv->{categories}|", "|$DEV{$t3_ip}{type}|") < 0);

       if ($line =~ /disk download/) { # stop monitoring
          $Agent::T3::SKIP{$t3_ip} = 1;
       }
       next if ($line =~ / sh\d+\[\d\]:.* Reset/); # caused by explorer

       if ($line =~ / sh\d+\[\d\]/) {  # user command was executed
          if ($line =~ /\s+disable/ || $line =~ /\s+download/ || 
              $line =~ /\s+unmount/ || $line =~ /vol\s+remove/ || 
              $line =~ /refresh/) {
            my $d1 = sprintf("%2.2d-%2.2d %s", Util->MTH($a[0]), $a[1], $a[2]);
            $Agent::T3::LAST_SHELL{$t3_ip} = $d1 
                  if (!$Agent::T3::LAST_SHELL{$t3_ip} || $Agent::T3::LAST_SHELL{$t3_ip} lt $d1);
          }
       }
       my $u1 = $a[6]; $knownT3 = 1;
       chop($u1) if (substr($u1,-1) eq ":");
       ($comp1, $comp2) = &comp($u1);
       $key  = $IP{$t3_ip} . ":$comp1.$comp2";
       $key0 = $IP{$t3_ip};

     } else {
       $key  = "t3:HOST";
       $key0 = "t3:HOST";
     }

     #                            ix  disk    t3b0   key    ip     key0
     $policies->run($err, $lines,\$x,$comp1, $a[3], $key, $t3_ip, $key0, $knownT3);
  }         
  my ($errs);
  foreach my $ip (keys %Agent::T3::SKIP) {
     my $dev1 = $Config->deviceByIP($ip);
     if ($dev1) {
       $write = 1;
       $dev1->{active} = "N";
       if (!$dev1->{skip}) {
         $dev1->{skip}   = time;
         Events->saveEvent("QS", $dev1->{type}, $dev1->{key}, "Monitoring stopped because of disk upgrade");
       }
       $errs .= "$dev1->{name}/$dev1->{ip},";
     }
  }
  if ($write) {
    $Config->save();
  }

  return ($err);
}


sub comp {
    my($b) = @_;
    my $type = "";
    $b =~ s/^Disabling //;  # remove this word, bug 4801791, bug in T3.

    if (substr($b,0,2) eq "un") {
        $type = "unit";

    }elsif ($b =~ /u(\d)d(\d+)/) {
        $type = "disk";
        $b =~ s/d0/d/;

    }elsif ($b =~ /u(\d)ctr/  ) {  
        $type = "controller";

    }elsif ($b =~ /^u(\d)l\d/  ) {
        $type = "loopcard";

    }elsif ($b =~ /u(\d)pcu\d/ ) {
        $type = "power";

    }elsif ($b =~ /^u(\d)p\d/) {
        $type = "port";

    }elsif ($b =~ /u(\d)mpn/) {
        $type = "midplane";

    }elsif ($b =~ /u(\d)b(\d+)/) {
        $type = "battery";

    }elsif ($b =~ /u(\d)vol/) {
        $type = (substr($b,6,1) eq "-")? "volume_disk":"volume";

    } else {
        $type = "enclosure"; $b = "unknown";
    }
  return ($type, $b);

}





1;
