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

#  $Name:  $ 
#  $Id: NetConnect.pm,v 1.5 2004/10/21 17:20:36 ccadieux Exp $

use PDM;
use PDM::ConfigFile;
use Carp;
use Message;
use Util;
use System;
use Util::Http;
use strict;

use base 'Provider';
sub revision {'$Revision: 1.5 $'}
use vars qw($PING_ERR);

sub description {'Net Connect'}

# return YES: success
#        ERR: Failure/Error
#        N/A: ping not available
#        
sub ping {
  my($class) = @_;
  my $CMD = "/opt/SUNWsrspx/bin/srspxrun";

  if (-x $CMD) {
     my($err, $rc) = Util->run_command("$CMD -p", "ping", 120);
     if ("@$rc" =~ /SUCCESSFUL PING/) {
        return "YES";
     } else {
        $PING_ERR = "$err @$rc";
        return "ERR";
     }
  } else {
     return "N/A";
  }
}


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

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

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

# http://shadow:8080/servlet/InsertService

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

  if ($q->{ACTION_update}) {
    my $package_base = System->getPackageInfo("", "SUNWnc01", "BASEDIR");
    if (!$package_base) {
      my $t1 = System->getPackageInfo("", "SUNWsrsvp", "_ALL_");
      if (!$t1->{VERSION}) {
         $warn = Html->warning("$L->{no_sunw}");
      }
    }

    ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read;
    my $old_active = $renv->{'pro.netconnect.active'};

    $renv->{'pro.netconnect.active'} = $q->{active}? "Y":"N";
    $renv->{'pro.netconnect.maxsize'}  = $q->{max};
    $renv->{'pro.netconnect.version'}  = $q->{version};

    PDM::ConfigFile->write( $renv, $dev, $host,$notifs);
    if ($q->{active} eq "Y" && $q->{active} ne $old_active) {
      open(O, ">" . System->get_home() . "/DATA/request_data_flush");
      close(O);
    }

    $err = Html->info($L->{err_1});
  }

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

  if ($renv->{'pro.netconnect.active'} eq "Y") {
    $active = "checked" ;
  } else {
    $info = "<font color=red><b>$G->{inactive}</b>";
  }
  my $max    = $renv->{'pro.netconnect.maxsize'} || "2000";
  my $version = Html->makeSelect("version", "=$L->{auto}|2=NetConnect 2.x|3=NetConnect 3.0|31=NetConnect 3.1", $renv->{"pro.netconnect.version"});
  my $scr = Html::Screen->new();
  $scr->add("$warn $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} , "<input type=checkbox name=active $active> $info"   ],
     [ f => $L->{max}    , "<input type=text name=max value=\"$max\" size=20>" ],
     [ f => $L->{trans_method}, $version ],
     ]);

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

}

sub findVersion {
  my($class, $version) = @_;

  my ($NET_RUN, $APEX);
  my $L = Labels->read('Provider')->section('netconnect');

  my $package_base = System->getPackageInfo("", "SUNWnc01", "BASEDIR");

  if ($version eq "31") {
     $APEX = System->get_home() . "/sbin/srs_send";

  } elsif ($version eq "2") {
     $NET_RUN = "$package_base/SUNWnc/bin/ncsend";

  } elsif ($version eq "3") {
     # use shuttle

  } elsif ($package_base) {
     $NET_RUN = "$package_base/SUNWnc/bin/ncsend";

  } else {
    my $t1 = System->getPackageInfo("", "SUNWsrspx", "_ALL_");
    if (!$t1->{VERSION}) {
       Debug->print2("  $L->{no_packages}");
       return (undef,undef,1);
    }
    # in the future, if ssp is not there , run a netc utility to install it.
    #
    my $t1 = System->getPackageInfo("", "SUNWsrssp", "_ALL_"); # storage
    if ($t1->{VERSION}) {
       # use shuttle
    } else { # =~  /03\.001/  (apex)
       #$APEX = "$t1/SUNWsrspx/bin/srsxfer" if ($t1);
       $APEX = System->get_home() . "/sbin/srs_send";
    }
  }
  return ($NET_RUN, $APEX);
}


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

  my($renv, $devices, $hosts, $notifs) = PDM::ConfigFile->read();
  my $version =  $renv->{'pro.netconnect.version'};
  my $L = Labels->read('Provider')->section('netconnect');

  Discover->provider($renv);  # discover which provider is active.

  if ($renv->{'pro.netconnect.active'} ne "Y") {
     Debug->print2("  $L->{not_active}");
     return;
  }
  my ($NET_RUN, $APEX, $return) = $pro->findVersion($version);
  return if ($return);

  if ($APEX && PDM->getEventCount() == 0) {
     &ack();
     return;
  }

  my($netfile) = "/opt/SUNWstade/DATA/SHUTTLE" ;  # prefix
                  #$renv->{'pro.shuttle.ifile'};

  my($netfile1) = $netfile . "1";   # high priority
  my($netfile3) = $netfile . "3";   # low priority

  my($max)     = ($renv->{'pro.netconnect.maxsize'} + 0) * 1000;
  $max = 10000000 if (!$max);

  rename $netfile1, "$netfile1.work";
  rename $netfile3, "$netfile3.work";

  open(W1, ">>$netfile1.work");
  open(W3, ">>$netfile3.work");

  my($size1) = (stat("$netfile1.work"))[7];
  my($size3) = (stat("$netfile3.work"))[7];
  my ($alarms, $events, %LOG);

  my $edocs     = PDM->getMessagesFromList($idList);

  foreach my $ed (@$edocs) {
     my $ev  = $ed->instances()->[0];
     my $actionable = $ev->value("Actionable");
     my $post;
     if ($actionable eq "TRUE") {
       $post = $ed->toC();
       if ($APEX) {
          &srs_send($ed);
          $alarms .= $post;
       } else {
          if ($size1 > $max) {
             close(W1);
             Debug->err(NETCONNECT => "File $netfile1 is full, cannot write anymore");
             last;
          }
          print W1 $post;
          $size1 += length($post);
       }
       $LOG{actionable}{$ev->value("TargetName")}++;
       Debug->print2("NetConnect : " . $ed->className . " " . $ed->description );

     } else {
       $post = $ed->toC;
       if ($APEX) {
          $events .= $ed->toC();
       } else {
          if ($size3 > $max) {
             close(W3);
             Debug->err(NETCONNECT => "File $netfile3 is full, cannot write anymore");
             next;
          }
          print W3 $post;
          $size3 += length($post);
       }
       $LOG{non_actionable}{$ev->value("TargetName")}++;
       Debug->print2("NetConnect : " . $ed->className . " " . $ed->description );
     }
  }
  System->logHash2(\%LOG, "Notifications", "NetConnect");
  close(W1);
  close(W3);
  
  if ($NET_RUN && -x $NET_RUN) {
     my $F1 = "$netfile1";  # use pid names since ncsend queue work
     my $F3 = "$netfile3";
     rename "$netfile1.work" , $F1;
     rename "$netfile3.work" , $F3;
     chmod 0666, $F1;
     chmod 0666, $F3;
     if (!(-z $F1)) {
        system("$NET_RUN -n nws $F1");
     }
     if (!(-z $F3)) {
        system("$NET_RUN -n nws $F3");
     }
  } elsif ($APEX) {
     &srs_send(0, $alarms);
     &srs_send(0, $events);

  # EXPECT writeNetConnect to be called
  } else {
     rename "$netfile1.work" , $netfile1;
     rename "$netfile3.work" , $netfile3;
     chmod 0666, $netfile1;
     chmod 0666, $netfile3;
  }

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

}

sub ack {
  my($ed) = @_;

  my $renv    = System->get_renv();
  my $version = "1.0";
  my $F       = "/tmp/srs_send.tmp";
  my $domain  = System->domain0();
  my $debug   = "-d" if (Debug->level() > 1);

  my $opts = "-D \"$domain\" $debug -l /tmp/srs_send.log -r 0 -v \"$version\" -f $F -s 99";
  open(W, ">/tmp/srs_send.tmp"); print W "HEARTBEAT"; close(W);

  my $com = System->get_home() .  "/sbin/srs_send $opts";
  Debug->print3("command: $com");
  my($err, $rc) = Util->run_command($com, "netconnect", 20);
}


sub srs_send {
  my($ed, $toc) = @_;

  my $renv    = System->get_renv();
  my $version = "1.0";
  my $F       = "/tmp/srs_send.tmp";
  my $domain  = System->domain0();
  my $debug   = "-d" if (Debug->level() > 1);

  my $opts = "-D \"$domain\" $debug -l /tmp/srs_send.log -r 0 -v \"$version\" -f $F";
  if ($toc) { 
     open(W, ">/tmp/srs_send.tmp");
     print W $toc;
     close(W);
     my $com = System->get_home() .  "/sbin/srs_send $opts";
     Debug->print3("command: $com");
     my($err, $rc) = Util->run_command($com, "netconnect", 20);
     Debug->print2("NetConnect srs_send:data Error: $err") if ($err);

  } elsif ($ed) {
     my $ev   = $ed->instances()->[0];
     my $sev  = $ev->value("Severity");
     my $desc = $ev->value("Description");
     my $discl= $ev->value("Disclaimer");

     open(W, ">/tmp/srs_send.tmp");
     print W $desc;
     if ($discl) {
       print W " ($discl)";
     }
     close(W);

     my $com = System->get_home() .  "/sbin/srs_send $opts -s $sev";
     Debug->print3("command: $com");
     my($err, $rc) = Util->run_command($com, "netconnect", 20);
     Debug->print2("NetConnect srs_send:event Error: $err") if ($err);
  }
}
  
1;
