#!/usr/bin/perl -I/opt/SUNWrasag21/lib
#  $Name:  $ 
#  $Id: rashttp,v 1.30 2001/10/17 22:37:40 ccadieux Exp $

use FindBin;
use Util;
use Debug;
use System;
use Event;
use Http;
use PDM::ConfigFile;
use PDM::Modules;
use Getopt::Std;
use Agent::T3Agent;
#use FibreGUI;

getopts("P:X", \%opts);

@ProviderList = (
   '.Net Connect Provider',
     'pro.shuttle.active',
     ['pro.shuttle.ifile', "/var/opt/SUNWrasag/DATA/SHUTTLE", 1],
     ['pro.shuttle.maxsize:10',"2000000"],
   '.SRS-2 Provider',
     'pro.srs2.active',
     ['pro.srs2.ip', "http://srs_station/StationServlets/XMLtoSRSServlet"],
     'pro.srs2.name',
     'pro.srs2.nat',
   '.Http Provider',
     'pro.http.active',
     ['pro.http.ip', "http://nscc:2000/nscc30/InsertService"],
     'pro.http.proxy',
     'pro.http.timeout:10',
          );

my($local_p);
if ($ARGV[0] eq "-D") {
  $HOME = $ARGV[1];
} else {
  $local_p = $FindBin::Bin;
  my($ix) = rindex($local_p, "/");
  $HOME = substr($local_p,0,$ix);
}


System->set_home($HOME);

$TO        = 20;  # time-out
$logfile   = "$HOME/log/http_access.log";
$CONF      = "$HOME/DATA/rasagent.conf";
%PRIO      = (1 => "High", 2 => "Medium", 3 => "Low", 9 => 'Medium+High');
$0         = $PRGMNAME = "rashttp";
$PASSW     = "$HOME/System/password";
$UNIXFILE = "/tmp/rassock_rashttp";
$RASPORT   = "7654";   
$BGCOLOR   = "#E0E0E0";
$LIGHT     = "#CCCCFF";

System->set_rasport($RASPORT);
System->set_testMode(0);
System->set_config($CONF);

if ($opts{X}) {
  open(O, "ps -ef|");
  while ($l = <O>) {
    $l = Util->ltrim($l);
    @a = split(/\s+/, $l);
    if ($a[7] =~ /\s+$PRGMNAME\s*$/ && $a[1] != $$) {
      print "Already there :$l \n";
      exit(1);
    }
  }
  close(O);
}



Debug->level(0);

$PDM_ConfigFile = PDM::ConfigFile->new({ hostid => System->hostid });

my($renv, $devices, $hosts, $notifs) = $PDM_ConfigFile->read;
System->set_renv($renv);


$util = Util->new({
       ConfigFile => $PDM_ConfigFile,
          RASPORT => $RASPORT,
               TO => $TO,
            debug => $debug,
                 });

open(O,$PASSW); $PASSWORD = <O>; close(O);


  $http = Http->new({
                   logfile => "",
                      root => "$HOME/htdocs",
                     login => "ras",
                  timeout  => $TO,
                  password => $PASSWORD,
                 });

  $master = Util->findMaster();
  if ($opts{X}) {
   eval {
     $http->unix_init($UNIXFILE);
     $http->unix_loop($util, $master);
   };
   if ($@) {
     Http::debug("error:$@");
   }
   Http::debug("Exiting");
     exit;
  }

  ($fun,$q, $post_data) = $http->stdin_process();

  if (0) {
  if ($master && !$q->{GET} && !$q->{PUT} ) { # master is defined, you are a slave
     print Http->text_header(
     "\n\n<center><h3>This is a SLAVE HOST AGENT, connect to the MASTER ".
     "with your browser<p> Go  to ".
     "<a href=http://$master:$RASPORT target=_top>MASTER HOST AGENT</a> now.\n"
       );
     exit;
  }}

  if ($fun) {
    if (defined(&$fun)) {
      print $http->text_header;
      &$fun($q, $post_data, $util);
    } else {
      $http->error(501, "Illegal Method", "function '$fun' not found");
    }
  }

exit;


sub luxdisc {
  my($out);
  print "\n<body bgcolor=$main'BGCOLOR><pre>";
  open(O, System->get_home() . "/bin/luxdisc 2>/tmp/luxdisc.err|");
  @a = <O>;
  close(O);
  open(E, "/tmp/luxdisc.err"); @err = <E>; close(E);
  print " <font color=red>@err</font>";
  print "@a";

}

sub menus {
  $D = System->get_home() . "/htdocs";
  my(@a, @b);
  foreach $f ('maint','monitor','log','system') {
     if (open(O, "$D/$f.html")) {
       @a = <O>; close(O);
       push(@b, @a);
       push(@b, "<br>");
     }
  }
  $menu = "@b";
  $menu =~ s/\<script /\<xscript /g;
  print $menu;
}

use GUI::Config;

sub welcome {
  my($out);
  my($renv, $dev, $host, $notifs) = PDM::ConfigFile->read();
  if (!$renv->{site_country}) {
     GUI::Config::upd();
     return;
  } 

  print "\n";
  print read_file("welcome");
  
  $out = Util->checkRasCrons();
  print "<p>
  <table border=0 cellspacing=2 cellpadding=1 width=80%><tr><td bgcolor=black>
  <table border=0 cellpadding=4 cellspacing=1 width=100% bgcolor=white>
   <tr><td bgcolor=$main'LIGHT><b>Verifying Crons</td>
   <tr><td>
    <big>$out
  </table></table>
   $testMode
  ";
  

}





#################################################################
#  RASAGENT MGR Operations
#################################################################

sub rasagent {

  print "\n";
  print "rasagent";
}

sub get_test {
  my($q, $post, $util) = @_;
  open(O, ">$HOME/DATA/get_test.post"); 
  $v = "";
  foreach $x (keys %$q) {
    $v .= "$x=$q->{$x}\n";
  }
  print O "GET :\n$v\n";
  print O "POST:\n$post\n"; 
  close(O);
  print "\nHello";
}

  
sub test {

  print "\n<pre>";
  open(O, "$HOME/bin/rasagent.pl -T web|");
  while ($l = <O>) {
     $l =~ s/</&lt;/g;
     print $l;
  }
  close(O);
}

sub installed_modules {
  my($q) = @_;
  print "\n";
}

sub read_file {
  my($f)  = @_;
  if (open(O,"$HOME/htdocs/$f.html") ) {
    @l = <O>; close(O);
    return "@l";
  } else {
    return "Error: $f: $!";
  }
}


sub config_file {
  my($q) = @_;
  print "\n";

  open(O, System->get_config());
 
  print "<body bgcolor=$main'BGCOLOR><pre>";
  
  while ($l = <O>) {
     print "$l";
  }
  close(O);

}




######################################################
#   TEST EMAIL
######################################################

sub test_email{
  my($q) = @_;
  my($err);

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

  my($default) = $notifs->[0]->{email};
  my($h) = header("Test Email","","","testemail");
  
  print "\n<body bgcolor=$main'BGCOLOR><center>&nbsp;";

  if ($q->{ACTION} eq "Submit") {
        ($renv, $dev, $host, $notifs) = PDM::ConfigFile->read();
        $MAILER = $renv->{mailer} || "/usr/bin/mail";
        $addr = $q->{email};
        if ($addr =~ /.+\@.+/) {
          $header= "From: Network_Storage_Agent\nSubject: Test Message\n\nCustomer: $renv->{customer}\n";
          open(O, "|$MAILER $addr");
          print O "$header"  . "-" x 50 . "\n" . $q->{message};
          close(O);
          $err = "<table border=0 bgcolor=white><tr><td><b><font color=green>Message delivered!</table>";
        } else  {
          $err = "<table border=0 bgcolor=white><tr><td><b><font color=red>Invalid Email Address, try again!</table>";
        }
  }
     

  $o =<<EOF;
  $h
$err
<table border=1 cellspacing=0 cellpadding=3 bgcolor=white width=90%>
<form  method=get>
<input type=hidden name=GO value=test_email>
<tr><td>
  Enter an Email Address and an optional Message for the Network Storage Agent to send an email.
</table>
&nbsp;
<table border=2 cellspacing=0 cellpadding=0 bgcolor=white width=90%><tr><td>
<table border=0 cellspacing=2 cellpadding=2 bgcolor=white width=100%>
 <tr><td align=right bgcolor=$main'LIGHT><b>&nbsp;Email Address: </td>
     <td><input type=text name=email size=30 value=\"$default\">
 <tr><td bgcolor=$main'LIGHT align=right><b>&nbsp;Message: </td>
     <td><input type=text name=message size=50>
</table></table>
<b>
<input type=submit name=ACTION value="Submit">
</form>
EOF

  print $o;
  
}


    
######################################################
#   LOCAL-NOTIFICATION MAINTENANCE
######################################################
sub find_multiple {
  my($q, $pref) = @_;
  my($ev) = ""; 
  my($l) = length($pref);
  my($all) = 0;
  foreach $x (keys %$q) {
print "$x=$q->{$x},";
    if (substr($x,0,$l ) eq $pref) {
        $ev .= substr($x,$l) . "|";
        $all = 1 if (substr($x,$l) eq "*") ;
    }
  }
  chop($ev);
  if ($all == 1) {
     return "*";
  } else {
     return $ev;
  }
}
  

# val can habe '|' in it.
#
sub select {
  my($values, $val, $m) = @_;
  my($sel, $x, $val0, $key, @a, $i);
  $sel = "";

  @a = split(/ *\| */, $values);
  foreach $x (@a) {
    $key = $val0 = "";
    $i = index($x,"=");
    if ($i >= 0) {
      $key = substr($x,0,$i);
      $val0 = substr($x,$i+1);
      if ($m) {
        $selected = (index($val, $key) >=0) ? "selected":"";
      } else {
        $selected = ($key eq $val) ? "selected":"";
      }
      $sel .= "<option value=\"$key\" $selected>$val0</option>";
    } else {
      if ($m) {
        $selected = (index($val, $x) >= 0) ? "selected":"";
      } else {
        $selected = ($x eq $val) ? "selected":"";
      }
      $sel .= "<option value=\"$x\" $selected>$x</option>";
    }
  }
  $sel .= "</select>";
  
}


######################################################
#   MODULE SPEED
######################################################

sub mod_speed {
  my($q) = @_;
  my ($sum, $x, $mins, $v, $secs, $a, $t);
  $a = Timelapse->readAll();
  my($sum, $sum2);
  foreach $x (keys %$a) {
         $v = $a->{$x}{avg};
         $t = $v->[1] / $v->[0];
         $sum += $t;
        $sum2 += $a->{$x}{last}[1];
  }
  $mins = int($sum / 60);
  $secs = $sum % 60;

  $mins2 = int($sum2 / 60);
  $secs2 = $sum2 % 60;
  return "<pre>Average Agent Runtime: $mins mins. and $secs secs.
   Last Agent Runtime: $mins2 mins. and $secs2 secs.";
}

sub save_event {
  my($a, $b, $c) = @_;
  open(O, ">>$HOME/DATA/gui_events");
  print O "$a\t$b\t$c\n";
  close(O);
}

sub pushSlaves {
  my($q) = @_;
  print "\n";
  require "GUI/Hosts.pm";
  GUI::Hosts::push_slaves($q);
  GUI::Hosts::list($q);
}


#
# called from the left_frame, generate the welcome to discovery page with buttons
# for each device type that can be discovered.
#
sub discover0 {
  my($q) = @_;

  my(@admins, $fun);
  print "\n";
  $header= &header("Device Discovery","","","discovery");

  @MODS = PDM::Modules->load("GUIAdmin");

  my($input) = "";
  foreach my $m (sort @MODS) {
    $fun = "GUIAdmin::${m}::discover";

    if (defined(&$fun)) {
      my $pk = "GUIAdmin::${m}";
      #my $name = $pk->description();

      $input .= "<input type=submit name=ACTION value=\" $m \">&nbsp; ";
    }
  }
  my($text) = &read_file("discover");
    
  $o =<<EOF;
<body bgcolor=$main'BGCOLOR>

<center>
&nbsp;
$header
<table border=1 cellspacing=0 cellpadding=4 bgcolor=white width=90%>
<form  method=get>
<input type=hidden name=GO value=discover>
<tr><td>
  $text
</table>
<b><p>
 <table border=1 width=90% cellspacing=0 bgcolor=#666699 cellpadding=6>
  <tr><td><b><center><table cellspacing=0 border=0>
     <tr><td bgcolor=white><b>$input</table></table></table>
</form>
EOF
  print $o;
}


#
# called to discover a specific type of device
#
sub discover {
  my($q, $post, $util) = @_;
  my($fun);
  print "\n";
  @MODS = PDM::Modules->load("GUIAdmin");

  if (($fun=$q->{PKG})) { # it's a callback
    if (defined(&$fun)) {
      $rc= &$fun($q,$port,$util);
      require "GUI/Devices.pm";
      GUI::Devices->list($q, $post, $util) if ($rc eq "DONE");
    }
    return;
  }

# find which button was pressed

  my($name) = substr($q->{ACTION},1, -1);
  my($fun) = "GUIAdmin::${name}::discover";

  if (defined(&$fun)) {
      $rc = &$fun($q,$port,$util);
      require "GUI/Devices.pm";
      GUI::Devices->list($q, $post, $util) if ($rc eq "DONE");
      return;
  }
  &discover0($q,$post,$util);
}
    

sub get_device {
  my($q, $post, $util) = @_;

  my($pk)   = "GUIAdmin/" .  uc($q->{type});
  my($func) = "GUIAdmin::" . uc($q->{type}) . "::getDevices";
  require "$pk.pm";
  if (defined(&$func)) {
     print &$func($q,$post,$util);
  } else {
     print "\nFunction $func not defined!";
  }
}


sub make_select {
  my($name, $l, $val) = @_;
  my($o, $ck);
  @a = split(/\|/, $l);
  $o = "<select name=$name><option value=\"\">[Select]</option>";
  foreach $x (@a) {
    @b = split(/=/, $x);
    $b[1] = $b[0] if (!$b[1]);
    $ck = ($b[0] eq $val)? "selected":"";
    $o .= "<option $ck value=$b[0]>$b[1]</option>";
  }
  $o .= "</select>";
  return $o;
}

sub make_radio {
  my($name, $l, $val) = @_;
  my($o, $ck);
  @a = split(/\|/, $l);
  foreach $x (@a) {
    @b = split(/=/, $x);
    $ck = ($b[0] eq $val)? "checked":"";
    $o .= "<input type=radio name=$name $ck value=$b[0]>&nbsp;<b>:$b[1]</b>&nbsp;&nbsp;";
  }
  return $o;
}
  
#
# REALLY A PUT STARTD
# Updates the config file of a slave.
#
sub get_startd {
  my($q) = @_;
  my($done, $current);
  Debug->log("get_startd");
  ($renv, $devs, $host,$notifs) = PDM::ConfigFile->read();

  if (!$q->{active}) {
    print "ER No active value!";
    return;
  }
  for ($x=0; $x <= $#$devs; $x++) {
    if ($devs->[$x]{name} eq $q->{name}) {
       $devs->[$x]{active} = $q->{active};
       $done = 1;
       last;
    }
  }

  if ($done) {
    PDM::ConfigFile->write( $renv, $devs, $host,$notifs);
    print "OK";
  } else {
    print "ER $q->{name} not found!";
  }
}

sub get_all_startd {

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

  for ($x=0; $x <= $#$devs; $x++) {
     print "$devs->[$x]{name}=$devs->[$x]{active}\n";
  }
}


sub info {
  my($m, $col) = @_;
  $col= "red" if (!$col);
  return "
<center>
<table border=0 cellspacing=4 cellpadding=2><tr><td bgcolor=$col>
<table border=0 cellspacing=2 cellpadding=3 bgcolor=white>
<tr><td><b><center>&nbsp;$m &nbsp;</table></table></center>";
}

# header("", "<options>", "help section");

sub header0 {
  my($m,$w, $opt, $move) = @_;

  $w = "90%" if (!$w);
  my($move) = "#$move" if ($move);
  my($o1, $o2);
  if ($opt) {
    $opt = "<td><form><td align=right nowrap> $opt</td><td></form></td>";
  }
  return "
<table border=0 cellspacing=0 cellpadding=2 width=$w>
  $o1
 <tr>
   <td><font size=+2 color=navy><b>$m</td>
   $opt
   <td align=right><b>[ <a href=doc.html$move>Help</a> ]</td>
   $o2
</table>";
}

sub header {
  my($m,$w, $opt, $move) = @_;

  $w = "90%" if (!$w);
  my($move) = "#$move" if ($move);
  my($o1, $o2);
  if ($opt) {
    $opt = "<td><form><td align=right nowrap> $opt</td><td></form></td>";
  }
  return "
<table border=0 cellspacing=0 cellpadding=2 width=$w>
  $o1
 <tr>
   <td><font size=+2 color=navy><b>$m</td>
   $opt
   <td align=right>
<script>
function o_win(x){
   var w=
    window.open('doc.html$move','help','scrollbars,resizable,width=650,height=600');
   w.focus();
}
</script>
<b>[ <a href=javascript:o_win()>Help</a> ]</td>
   $o2
</table>";
}


sub select_frequency {
  my($renv) = @_;
  my($frequency);
  $frequency = "<select name=frequency><option value=\"\">[Select]</option>";
  foreach $x (5,10,15,20,30,40,50,60,90,120) {
    $sel = ($renv->{frequency} == $x) ? "selected":"";
    $ss = ($x == 1) ? "":"s";
    $frequency .= "<option $sel value=$x>$x minute$ss</option>";
  }
  $frequency .= "</select>";
  return $frequency;
}

sub find_devices {
  my(@MODS, @dirs, $x);

  my($list) = Util->findMethods("GUIAdmin", undef, "isDevice");

  foreach my $f (sort @$list) {
    my(@b) = split(/=/, $f);
    if ($b[1]) {
       push(@MODS, $b[0]);
    }
  }
  @MODS = sort(@MODS);
  return \@MODS;
}

sub findSelectableAgents {
  my(@MODS, @dirs, $x);

  my($list) = Util->findMethods("Agent","Agent", "isSelectable");

  foreach my $f (sort @$list) {
    my(@b) = split(/=/, $f);
    if ($b[1]) {
      push(@MODS, lc(substr($b[0],0,-5)) . "=$b[1]" );
    }
  }
  return \@MODS;
}


sub server {
  my($q) = @_;

  print "\n";
  $info = "";

  if ($q->{ACTION} eq " Update ") {
    if (length($q->{pass}) < 4) {
      $info = &info("Password must be at least 4 characters <br>Password not changed!");

    } else {
      open(O,$PASSW);
      $o = <O>; close(O);
      if ( crypt($q->{old}, substr($o , 0, 2)) ne $o) {
         $info = &info("Old password is Incorrect, password not updated!");

      } elsif (open(O,">$PASSW")) {
         my($pass1) = crypt($q->{pass}, ((sprintf("%x", time | $$)) =~ /(..)$/, $1));
         print O $pass1;
         close(O);
         $info = &info("WebServer password updated!");
      } else {
         $info = &info("Cannot update password file: $! ");
      }
    }
  }
  $h = &header("WebServer Maintenance");

  $o =<<EOF;
<body bgcolor=$main'BGCOLOR>
<form  method=get>
 <input type=hidden name=GO value=server>
<center>
$h
$info
<table border=2 cellspacing=2 width=90% bgcolor=white><tr><td>
<table border=0 cellspacing=2 width=100%>
<tr><td colspan=2 bgcolor=#666699><b><font color=white>&nbsp;Password Maintenance</td>
<tr><td bgcolor=$main'LIGHT width=30% align=right>User :</td><td><b>ras</td>
<tr><td bgcolor=$main'LIGHT width=30% align=right>Enter OLD password :</td>
    <td><input type=password name=old size=10  maxlength=10 value="">
<tr><td bgcolor=$main'LIGHT width=30% align=right>Enter NEW password&nbsp;<br> (min 4 chars.) :</td>
    <td><input type=password name=pass size=10  maxlength=10 value="">
</table>
</table>
<b>
<input type=submit name=ACTION value=" Update ">
</form>
EOF

  print $o;
}

sub get_color {
  my($category, $att, $value) = @_;
  return "" if (!$value);
  if (index("degraded",lc($value)) >= 0) {
     return "bgcolor=#F0F0C0";
  } elsif (index("failed", lc($value)) >= 0) {
     return "bgcolor=#F0C0C0";
  }
  return "";
}


# displays configuration or state
sub display_device_status {
  my($x, $category, $event_type, $name, $id_name) = @_;
  my($att, $att2, $p2, $p);
  
#  print "</center><pre>" . Dumper($x); return;
  my($head) = ""; 
  my($details) = "";
  foreach $att (sort keys %$x) {
     if ($att eq "event_info") {
        $p = $x->{$att};
        foreach $att (sort keys %$p) {
          $head .= " $att=$p->{$att},";
        }
     } elsif (!ref($x->{$att})) {
        $head .= " $att=$x->{$att}, ";
     }
  }
  $x = $x->{elem};
  foreach $att (@$x) {
       $type = $att->{elem_type};
       @xx = split(/,/, $id_name); $id = "";$id_attr = "";
       foreach $xx1 (@xx) {
          if (defined($att->{$xx1})) {
            $id = $att->{$xx1}; $id_attr = $xx1;
            last;
          }
       }
       ($col1, $col2)= &two_cols($att, $id_attr);
       $details .= "<tr><td  bgcolor=#666699 width=25%>
                  <font color=white><b><center>$type $id</td><td>
               <table border=0 width=100% cellpadding=0>
                  <tr><td valign=top width=50%>$col1</td><td valign=top>$col2</table>";
       $cnt = 0;
  }
  print "
    <table border=2 cellspacing=2 cellpadding=1 width=90% bgcolor=white><tr><td>
    <table border=0 cellspacing=1 cellpadding=0 width=100% bgcolor=$main'LIGHT>";
  $event = Event->get_description($a[1]);
  print "<tr><td bgcolor=#666699 colspan=2><font color=white><b>&nbsp;$event: $a[0] $a[2]</td>
    <tr><td colspan=2>
        <table border=1 cellspacing=0 cellpadding=4 width=100%><tr><td>$head</table></td>
    $details
    </table></table>&nbsp;<p>";

}

# SLAVE GENERATE ANSWER to httpi-master

sub two_cols {
  my($p, $skip) = @_;
  my(@save) = ();
  my($att2, $val, $xx, $half, $col1, $col2);

  foreach $att2 (sort keys %$p) {
      next if ($att2 eq "elem_type" || $att2 eq $skip);
      $val = $p->{$att2};
      $val = substr($val,0,30) if ($att2 eq "volWWN");
      push(@save, "$att2=$val");
  }
  $half = int($#save/2);
  for ($xx=0; $xx <= $half; $xx++) {
     $col1 .= "$save[$xx]<br>";
  }
  for ($xx=$half+1; $xx <= $#save; $xx++) {
     $col2 .= "$save[$xx]<br>";
  }
  return ($col1, $col2);
}




# slave returns a list of instrumentation reports.

sub get_run_file_list {
  my($q, $port, $util) = @_;
  my($created, $VAR1);

#  my($xref) = Util->getXref();

  print "OK";
  
  opendir(O, "$HOME/DATA/OLD_REPORTS");
  @a = readdir(O); closedir(O);
  foreach $file (@a) {
     next if ($file !~ /.+:.+/);
     $created = Util->get_file_created("$HOME/DATA/OLD_REPORTS/$file");
     @b = split(/:/, $file);
     next if ($q->{exclude} && index($q->{exclude}, $b[1]) >= 0);
     open(O1, "$HOME/DATA/OLD_REPORTS/$file");
     my(@a) = <O1>; close(O1);
     eval "@a";

     if (!$q->{include} || ($q->{include} && index($q->{include}, $b[1]) >= 0)) {
       my($name) = $VAR1->{_id}{name};
       print "$file||$created||$name\n";

     }
  }
}

sub get_run_file {
  my($q, $port, $util) = @_;
  
  if (open(O, "$HOME/DATA/OLD_REPORTS/$q->{file}")) {

     while ($l = <O>) {
        print  $l;
     }
     close(O);
  } else {
     print "ERR File $q->{file} does not exist!";
  }
}

sub get_file_exist {
  my($q, $port, $util) = @_;
  print "\n";
 
  if (-f $q->{file} || -d $q->{file}) {
     print "OK";
  } else {
     print "ERR";
  }
}


sub get_logfile {
  my($q, $post) = @_;
  my($out); 
  print "\n";
  if (!open(O, "$HOME/log/errors.log")) {
    print "ERR Cannot read errors.log: $!\n";
    return;
  } else {
    print "OK\n";
  }
  $cnt = 0; $MAX = $q->{max} || 25;
  while ($l = <O>) {
     $cnt = 0 if ($cnt > $MAX);
     $S[$cnt] = $l;
     $cnt++;
  }
  close(O);
  
  $cnt2 = $cnt - 1;
  $cnt2 = $MAX if ($cnt < 0);
  $cnt3 = 0;
  while ($cnt3 < $MAX) {
    $out .=  $S[$cnt2];
    $cnt2--; $cnt3++;
  }
  print $out;
}


##################################################
#  PUT HTTP : RECEIVE INFORMATION (POST), ANSWER STATUS
##################################################

sub put_config {
  my($q, $post) = @_;

  if (open(O, ">" . System->get_config() . ".push")) {
     print O $post;
     close(O);
     print "OK\n";
  } else {
     print "Err: Cannot open rasagent.conf: $!\n";
  }
}

# NOT USED, replaced by a pull from the master
sub put_slave_data {    # store slave data on master file.
  my($q, $post) = @_;

  my($f) =  "$HOME/data/SLAVE/LOG";
  if (! open(O, ">>$f")) {
    print "ER-" . &log2("Error with $f: $!");
  } else {
    my($l) = length($post);
    print O sprintf("%10.10d", $l);
    print O $post;
    close(O);
    print "OK-" . length($post);
  }
  chmod 0666, $f;

}

# 
# this is executed on the slave at the request of the master and empties the 
# SLAVE_DATA file where the rasagent_slave wrote all new events.
#
sub get_slave_data {
  my($q) = @_;

  my($f) =  "$HOME/DATA/SLAVE_DATA";
  print "\n";
  unlink "$f.P";
  rename $f, "$f.P";
  open(O, "$f.P");
  while ($l = <O>) {
    print $l;
  }
  close(O);

}

# Executed by http at the request of the Shuttle Provider
# will return all Messages that are old enough.

sub get_eventDocs {
  my($q) = @_;
  my($eds) = PDM::SAFread({ dir => "Shuttle"});
  print "\n<pre>\n";

  foreach $ed (@$eds) {
     print "+D\t" . $ed->fileNo . "\n";
     print $ed->toC;
     print "-D\n";
  }
}


##################################################
#  GET HTTP : REQUEST INFORMATION
##################################################

#
# called by a slave to register a new host
#
sub get_new_host {
  my($q) = @_;
  my($slaveh, $h, $hid, $x, $found, $foundno);
#  print "\n";


  $hid = System->hostid();
  $slaveh = $q->{hostid};

  if ($slaveh && $slaveh ne $hid) {
      ($renv, $dev, $hosts, $notifs) = PDM::ConfigFile->read();
      $found = 0; $foundno = -1;
      for ($x=0; $x <= $#$hosts; $x++) {
         $h = $hosts->[$x];
         if ($h->{hostid} eq $slaveh || ($h->{hostname} eq $q->{ipname}) ) {
            $found = 1; $foundno = $x;
            last;
         }
      }
      if (!$found && $q->{ipname} ) {
        &save_event("AH", $slaveh, $q->{ipname});
        $x = $#$hosts + 1;
        $hosts->[$x]{categories} = "a3500fc|a5k|t3|switch|host";
        $hosts->[$x]{_name}    = "host" . ($x+1);
        $hosts->[$x]{hostname} = $q->{ipname};
        $hosts->[$x]{hostid}   = $slaveh;
        $hosts->[$x]{active}   = "Y";
        $hosts->[$x]{frequency}= 3;
        $hosts->[$x]{contract} = "";
        $hosts->[$x]{ip}       = $q->{ipname};
        $hosts->[$x]{ipno}     = Util->name2ip($q->{ipname}) || $q->{ip};
        $hosts->[$x]{logfile}  = "/var/adm/messages";
        $hosts->[$x]{t300logfile} = "";
        $hosts->[$x]{st4logfile} = "/var/opt/SUNWvtsst/logs";
        $hosts->[$x]{ping}     = "";
      }
      if ($found) {
        $hosts->[$foundno]{hostid}   = $slaveh;
        $hosts->[$foundno]{active}   = "Y";
      }
      PDM::ConfigFile->write( $renv, $dev, $hosts, $notifs);
  }
  print $hid;
}

sub get_hostid {
  my($q) = @_;

#  print "\n";
  $hid = `/usr/bin/hostid`; chop($hid);
  print $hid;
}

sub get_isMaster {
  my($q) = @_;
  if (-f "$HOME/DATA/MASTER") {
     print "N";
  } else {
     print "Y";
  }
}



sub get_start {
  my($q) = @_;

#  print "\n";
  if (-f "$HOME/DATA/start"){
    print "Yes";
  } else {
    print "No";
  }
}

sub put_start {
  my($q) = @_;
  if ($q->{start} =~ "Y") {
    open(O, ">$HOME/DATA/start");
    print O "Y";
    close(O);
  } else {
    unlink "$HOME/DATA/start";
  }
  print "OK";
}


sub get_test2 {
  my($q) = @_;

  print "\n";

}

sub log2 {
  my($v) = @_;
  open(OO , ">>$HOME/log/httpi.log");
  print  OO  Util->today . "\t$v";
  close(OO);
  print "\n $v";
}

# GET_CONFIG: THIS WILL SERVE A CUSTOM CONFIG TO ANY SLAVE who asks

sub get_config {
  my($q, $post, $util) = @_;
  my($name, $config);
  print "\n";

  return "" if (!$q->{hostid});

  print PDM::ConfigFile->getSlaveConfig($q->{hostid}, 1);
}



sub log_change {
  my($info, $type) = @_;
  $type = "Warning" if (!$type);

  open(LOG, ">>$HOME/data/ras_server.log");
  $info =~ s/\n/ /g;
  my($today) = Util->today("YMDH");
  $out = "<log_line line_type=\"$type\" date=\"$today\" text=\"$info\" />\n";
  print LOG $out;
  close(LOG);
}

################################################
#    LOCAL LOG DISPLAY
################################################

sub event_log1 {
  my($q, $post, $util) = @_;
  my($dd);


  @a = split(/\./, $q->{file});
  $desc = Event->get_description($a[0]);
  $h = &header("Network Storage Agent Events: $desc");

  print "\n<body bgcolor=$main'BGCOLOR><center>&nbsp;$h ";
  $f = "<font color=white><b>";
  print <<EOF;
  <table border=1 cellspacing=0 cellpadding=1 bgcolor=white width=90%>
  <tr bgcolor=#666699>
      <th>$f Date</td>
      <th>$f Category</td>
      <th>$f Type</td>
      <th>$f Host</td>
      <th>$f IP</td>
      <th>$f Key</td>
EOF

  my($f) =  "$HOME/data/EVENTS/$q->{file}";
  open(O, $f) || print " Error reading $f: $!";
  my($type);
  
  $cnt = 0;  $MAX = 20; @S = ();
  while ($l = <O>) {
       $cnt = 0 if ($cnt > $MAX);
       $S[$cnt] = $l;
       $cnt++;
  }
  close(O);
  $cnt2 = $cnt - 1; $tot = $cnt;
  $cnt2 = $MAX if ($cnt < 0);
  $cnt3 = 0;
  while ($cnt3 < $MAX && $tot > 0) {
     $l = $S[$cnt2];
     $dd = XMLinput($l, (keeproot => 0, keyattr => '', forcearray => ['elem','data','update'] )) || {};
     $l =~ s/\t/\n/g;
     $text = Event->display($l,1);
     if (index($dd->{modes}, "n") >= 0) {
       $type = "New&nbsp;info";
     } elsif (index($dd->{modes}, "u") >= 0) { 
       $type = "Changes";
     }
     $info = $dd->{event_info};
     $text =~ s/\n/<br>/g;
     print "<tr>
        <td nowrap><small>&nbsp;$info->{date}</td>
        <td>&nbsp;$info->{category}</td>
        <td><small>&nbsp;$type</td>
        <td><center>$info->{hostid}</td>
        <td>&nbsp;$info->{ip}</td>
        <td><small>&nbsp;$info->{key_type}:$info->{key}</td>
        <tr><td colspan=6>$text </td>";
     $cnt2--; $cnt3++; $tot--;
  }
  print "</table>";
  
}

sub event_log {
  my($q, $post, $util) = @_;
  print "\n<body bgcolor=$main'BGCOLOR><center>";
  $h = &header("Local Event Log");
 
  $o =<<EOF;
$h

<table border=2 cellspacing=2 width=80% bgcolor=white><tr><td>
<table border=0 cellspacing=2 width=100% bgcolor=#F0F0F0>
<tr><td colspan=2 bgcolor=#666699><b><font color=white>&nbsp;Available Local Logs</td>
<tr bgcolor=#D0D0D0><td>Name</td>
   <td>Last Update</td>
<tr>
EOF

  $cnt = -1;
  opendir(O, "$HOME/data/EVENTS");
  @a = readdir(O); closedir(O);
  foreach $x (@a) {
     next if ($x =~ /^\./);
     @xx = split(/\./, $x);
     $desc = Event->get_description($xx[0]);
     push(@M, "$desc|$x");
  }
  foreach $x0 (sort @M) {
     ($desc, $x) = split(/\|/, $x0);
     $mod = Util->get_file_created("$HOME/DATA/EVENTS/$x");
     $o .= "<tr><td><a href=/?GO=event_log1&file=$x>$desc</a></td><td>$mod</td>" ;
  }
  $o .= "</table></table>";

  print $o;

}


sub get_message_log {
  my($q) = @_;
  my(@a);
  print "\n";
  if (open(O, $q->{file})) {
     seek(O,-20000, 2);
     $l = <O>;
     while ($l = <O>) {
        push(@a, $l);
     }
     close(O);
     for ($x=$#a; $x >= 0; $x--) {
       print "$a[$x]<br>";
     }
     close(O);
  } else {
     print "Cannot read $q->{file}: $!<br>";
  }
}





#####################################
#    Agents
#####################################

@MODULES = ();
%MODULES = ();

sub register {
   my($module) = @_;
   push(@MODULES, $module);
   $MODULES{ref($module)} = $module;
   open(REG, ">$HOME/log/modules.log");
   print REG $module->{name} . "\n";
   close(REG);
}



# HTTPi Hypertext Tiny Truncated Process Implementation
# Copyright 1999 Cameron Kaiser # All rights reserved # Please read LICENSE
# Do not strip this copyright message.
