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

#  $Name:  $ 
#  $Id: Brocade.pm,v 1.4 2004/11/01 20:39:05 mckenney Exp $


use base 'Health';
use NWS::Brocade;
use Ilist;
use Message;
use Report;
use Catalog;
use Events;
use strict;
use Debug;

sub revision {'$Revision: 1.4 $'}

#####################################################

sub all_logic {
  my($hm, $report) = @_;
  my($ev, $ed, $pertains, $x ,$y, $contain, $sd);
  my($orep, $key);
  my($rep)     = $report->content;
  my($oreport) = PDM->getOldReport($report->fileKey);
  my($ip)      = $report->id('ip');
  my($name)    = $report->name;
  my $wwn      = $report->id('deviceName');
  my($id)      = $report->id('display');
  my($log)     = $report->log();
  if (!$wwn) {
     Debug->errNoRepeat(T3_NO_KEY => $ip, 24, "Switch ($name/$ip) cannot be identified");
     return;
  }

  CIM->version("1.1");
  $DB::single = 1;

  return if ($hm->connectionEvent($wwn, $report, {method => 2} ));

  my $freq  = System->get_renv()->{audit_freq} || 7;
  my $audit = System->get_audit() ? "YES" : Timer->isXdays("Audit$wwn", $freq);

  if (!$oreport || $audit eq "YES" ) {  
     # new Brocade or audit time.
     my($etype) = $audit eq "YES" ? "brocade.AuditEvent" : "brocade.DiscoveryEvent";
     my($title) = $audit eq "YES" ? "Auditing a":"Discovered a new";
     my($dt)    = "A" if (!$audit);
     Grid->setCode($etype);
     $ev = CIM::Instance->new('NWS_Event', [
                  [ EventType   => $etype ],
                  [ Target      => "brocade:$wwn" ],
                  [ TargetName  => $id  ],
                  [ SourceIP    => $ip  ],
                  [ EventId     => PDM->getEventSequence  ],
                  [ Description => "$title Brocade Switch called $id"],
                  [ Data        => $hm->serial($rep) ],
                         ]);

     $sd = Events->sourceDetector({ event => $ev , host => 1, rep => $rep});
      
     my($p) = NWS::Brocade->newSystem($rep);

     $pertains = CIM::Instance->new('NWS_EventPertainsToSystem', [
                  [ Event       => $ev  ],
                  [ Element     => $p->[0] ],
                  [ DiscoveryType => $dt],
                    ]);

     my($monitors) = CIM::Instance->new('NWS_AgentMonitors', [
                  [ Agent       => $sd->[0]  ],
                  [ Element     => $p->[0] ],
                    ]);

     $ed = Message->new( { id        => $report->id,
                            instances => [$ev, @$sd,  @$p, $monitors, $pertains ],
                            severity  => Message::SEVERITY_NORMAL });

     PDM->saveMessage($ed);
     if ($audit) {  # dump stats.

        Grid->setCode("brocade.Statistics");
        $ev = CIM::Instance->new('NWS_Event', [
                  [ EventType   => 'brocade.Statistics'  ],
                  [ Target      => "brocade:$wwn" ],
                  [ TargetName  => $id  ],
                  [ SourceIP    => $ip  ],
                  [ EventId     => PDM->getEventSequence  ],
                  [ Description => "Statistics about Brocade Switch $id :"],
                  [ Data        => Util->nnl($rep->toStringP('port.\d+.stats'))],
                         ]);

        $sd = Events->sourceDetector({ event => $ev });

        my($system_key) = CIM::Key->new( ['NWS_System', 
                    'Name'            =>$rep->get('id.wwn'), 
                    CreationClassName => 'NWS_System']);

        $pertains = CIM::Instance->new('NWS_EventPertainsToSystem', [
                  [ Event       => $ev  ],
                  [ Element     => $system_key ],
                    ]);

        $ed = Message->new( { id        => $report->id,
                            instances => [$ev, @$sd, $pertains ],
                            severity  => Message::SEVERITY_NORMAL});

        PDM->saveMessage($ed);

     }
  }
  return if (!$oreport);


  $orep = $oreport->content;
  $hm->locationChangeEvent($report, $rep, $orep, $wwn);

  my($physicalFrame) = CIM::Key->new( ['CIM_PhysicalFrame',   # key of the frame
                        Tag               => $rep->get("id.wwn") ,
                        CreationClassName => 'CIM_PhysicalFrame' ]);

  $hm->fcEvent($rep->{FC_COUNTERS}, $orep->{FC_COUNTERS});

  my($PORTS) = $rep->get('port.count');

# check if port state has changed

  my($comp);
  for ($x=0; $x <= $PORTS; $x++) {
     $comp = "port.$x"; # . sprintf("%3.3d", $x);
     Grid->setCode("brocade.StateChangeEvent.port");
     my $extra;
     if (exists $rep->{"$comp.state.AdmStatus"}) {
        $extra = "Admin-Status is '" . $rep->{"$comp.state.AdmStatus"} . "'";
     }
     $hm->stateChangeEvent($comp, 'status', $report, $rep, $orep, 'CIM_Card', "$wwn.$comp", $wwn,
                   {info => $extra});
  }
#
# check sensors for changes
#
  my($type, $status, $ostatus, $val, $oval);
  foreach my $el ('temperature','fan', 'power-supply') {
    for ($x=1; $x <= 20; $x++) {
      $type    = $rep->get("sensor.$el.$x.info");
      last if (!$type);
      if ($el eq "temperature") {
        Grid->setCode("brocade.AlarmEvent.sensor.temperature");
      } elsif ($el eq "fan") {
        Grid->setCode("brocade.AlarmEvent.sensor.fan");
      } else {
        Grid->setCode("brocade.AlarmEvent.sensor.power");
      }
      $hm->mapValueChangeEvent($report, $orep, "BROCADE", "sensor.$el.$x", "status", $id, $id, $wwn, "sensor.$el.status");
    }
  }

  Grid->setCode("brocade.AlarmEvent.port.statistics");
  $hm->portStatEvents($report, $PORTS, $rep, $orep);


  my $olduptime = $orep->get("swSystem.swBootDate");
  my $newuptime =  $rep->get("swSystem.swBootDate");

  if ($olduptime && $newuptime && ($olduptime ne $newuptime)) {
     if($olduptime < 4286304000){
       # this isn't within a day of a counter wrap so report change

       Grid->setCode("brocade.AlarmEvent.system_reboot");
       $hm->valueChangeEvent("system.uptime", "", $report, $wwn, "Switch rebootDate changed on $id from '$olduptime' to '$newuptime'", 1, "system_reboot");
     }
  }

      
}

  
sub status {
   my($hm, $rep, $orep, $comp) = @_;
   my($map) = PDM->getDeviceStateMap("brocade.availability");
   Debug->print3("brocade: $comp");

   my($status)  = $rep->getState("$comp.state.OpStatus");
   my($ostatus) = $orep->getState("$comp.state.OpStatus");
   $status = $ostatus if ($status eq '[undefined]');
   $status      =~ s/\(\d+\)$//;
   $ostatus     =~ s/\(\d+\)$//;

   my($old, $new, $sev, $act) = 
      $map->transition("state.OpStatus.$ostatus", "state.OpStatus.$status", $orep, $rep);

   return ("$ostatus", "$status",$old, $new, $sev, $act );

}



1;

