package Client::Config;
use Client;
use System;
use strict;
use Agent;
use GUIAdmin;
use Events;
use Util::Http;


# key = t3:value

sub getDeviceInfo {
  my($q) = @_;
  my $key = $q->{key};

  print Client->http_OK();
  my $comment = Util->deserialize("Comments.txt") || {};
  print "<INFO>$comment->{$key}</INFO>\n";
}


# key  = t3:value
# info = text

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

  print Client->http_OK();
  my $comment = Util->deserialize("Comments.txt") || {};

  $q->{info} =~ s/\r//g;
  $q->{info} =~ s/\n /\n/g;
  $q->{info} =~ s/<\//< \//g;
  $comment->{$q->{key}} = $q->{info};

  Util->serialize("Comments.txt", $comment);
  print "<INFO>$q->{key}</INFO>\n";

}

#==================================================
#  ENVIRONMENT (setup, timeouts, providers, frequency etc..)
#==================================================
use vars qw($SKIP);
$SKIP= ",edition,html_login,sdt,se_slave,solution,solution_model,sun_help,time_added,topo_mode,version,GO,";

sub getRenv {
  my($q) = @_;
  my $filter = $q->{filter};
  
  my $renv = System->get_renv();
  print Client->http_OK();
  print "<ENV>\n";
  foreach my $e (sort keys %$renv) {
     next if ($filter && ($filter ne substr($e,0,length($filter))  ));
     next if (substr($e,0,4) eq "GSV_" || index($SKIP, ",$e,") >= 0);

# replace the characters which will destory xml format
     my $value =  $renv->{$e};
     $value =~ s/>/&gt;/g;
     $value =~ s/</&lt;/g;
     $value =~ s/"/&quot;/g;
     $value =~ s/&/&amp;/g;

     print "  <VALUE ID=\"$e\">$value</VALUE>\n";
  }
  print "</ENV>\n";
}

sub setRenv {
  my($q) = @_;
  print Client->http_OK();
  print "<ENV>\n";

  my($renv, $devs, $hosts,$notifs) = PDM::ConfigFile->read();
  foreach my $e (keys %$q) {
     next if ($e eq "GO" || substr($e,0,6) eq "COOKIE");
     next if (index($SKIP, ",$e,") >= 0);
     if($e =~ /^pro(.+)active/){
        my $prov = $1;
	my $ori_active = $renv->{'pro.${prov}.active'};
	my $active = $q->{$e};
	
	if (uc($active) eq "Y" && uc($active) ne $ori_active) {
           $renv->{request_data_flush} = time;
        }
     }
     $renv->{$e} = $q->{$e};
     print "<VALUE ID=\"$e\">$q->{$e}</VALUE>\n";
  }
  print "</VALUE>\n";
  print "</ENV>\n";
  PDM::ConfigFile->write($renv, $devs, $hosts, $notifs);
}




#==================================================
#  EMAIL
#==================================================

#
# getEmail
# getEmail&email=ccadieux@central
#
sub getEmail {
  my($q) = @_;

  my $name = $q->{email};

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

  print Client->http_OK();
  print "<NOTIFICATION>\n";

  foreach my $n (@$notifs) {
     next if ($name && $n->{email} ne $name);
     print "  <NOTIF ID=\"$n->{_name}\">\n";
     foreach my $e (sort keys %$n) {
        next if (index(",groups,language,event,apply_filters,", ",$e,") >= 0);
        print "    <VALUE ID=\"$e\">$n->{$e}</VALUE>\n";
     }
     print "  </NOTIF>\n";
  }      
  print "</NOTIFICATION>\n";
  
}


#
# 
# updateEmail&_name=notification1&email=newvalue&device=t3
#

sub updateEmail {
  my($q) = @_;
  my $key = $q->{_name};

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

  print Client->http_OK();
  print "<NOTIFICATION>\n";
  my($UPD);

  my $no = substr($key,12) - 1;
  $notifs->[$no]{_name} = "";

  print "<VALUE ID=\"$key\">updated</VALUE>\n";
  foreach my $el (keys %$q) {
       next if ($el eq "GO" || substr($el,0,6) eq "COOKIE");
       $notifs->[$no]{$el} = $q->{$el};
  }

  PDM::ConfigFile->write($renv, $devs, $hosts, $notifs);

  print "</NOTIFICATION>\n";
}

# 
#  deleteEmail&_name=notification1

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

  my $key = $q->{_name};
  my($renv, $devs, $hosts,$notifs) = PDM::ConfigFile->read();

  print Client->http_OK();
  print "<NOTIFICATION>\n";

  my $no = substr($key,12) - 1;
  $notifs->[$no]{_name} = "";

  print "  <VALUE ID=\"$key\">deleted</VALUE>\n";
  print "</NOTIFICATION>\n";

  PDM::ConfigFile->write($renv, $devs, $hosts, $notifs);
  
  
}


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

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

  print Client->http_OK();
  print "<NOTIFICATION>\n";

  my $no = $#$notifs +2;

  push(@$notifs, 
               {
                    _name  => "notification$no",
                    active => $q->{active}   || "Y",
             apply_filters => "N",              
                    device => $q->{device}   || "*",
                    email  => $q->{email},
                    event  => "*",
                   no_grid => $q->{no_grid}  || "N",
                  priority => $q->{priority} || "*",
                  script   => $q->{script},
                  skip_agg => exists $q->{skip_agg} ? $q->{skip_agg} : 1,
                  type     => $q->{type} || "Email",
               });

  print "<VALUE ID=\"$no\"></VALUE>\n";

  PDM::ConfigFile->write($renv, $devs, $hosts, $notifs) ;

  print "</NOTIFICATION>\n";
}

sub getAgents {
  my($select);
  my($cat) = Agent->findSelectableAgents();
  my ($c0);
  
  print Client->http_OK();
  print "<AGENTS>\n";
  foreach $c0 (@$cat) {
     my ($c, $c2) = split(/\=/, $c0);
     my $n1 = Util->abb(lc($c) . ".medium") || $c;
     print "  <VALUE ID=\"$c\">$n1</VALUE>\n";
  }
  print "</AGENTS>\n"; 
}

#========================================
# MONITORED DEVICES
#========================================
  
#
# List all devices (an instrumentation report may not be available yet for these devices).
#
sub listDevices {
  my($q) = @_;
  print Client->http_OK();
  my ($renv, $devs, $hosts, $notifs)  = PDM::ConfigFile->read();

  print "<DEVICES>\n";

  foreach my $d (@$devs) {
     print "  <DEVICE ID=\"$d->{_name}\">\n";
   
     if(!$d->{host}) {
       $d->{host} = $renv->{hostname};
     }
      
     foreach my $el (keys %$d) {
        next if ($el eq "_name");
        print "    <VALUE ID=\"$el\">" . Client->xmlEncode($d->{$el}) . "</VALUE>\n";
     }
     print "  </DEVICE>\n";
  }  
  if (!$q->{skip_hosts}) {
    my $ip = Util->name2ip();
    print "  <DEVICE ID=\"H0\">\n";
    print "    <VALUE ID=\"active\">$renv->{active_agent}</VALUE>\n";
    print "    <VALUE ID=\"name\">$renv->{hostname}</VALUE>\n";
    print "    <VALUE ID=\"ipno\">$ip</VALUE>\n";
    print "    <VALUE ID=\"type\">host</VALUE>\n";
    print "    <VALUE ID=\"key\">$renv->{hostname}</VALUE>\n";
    print "    <VALUE ID=\"class\">host</VALUE>\n";
    print "  </DEVICE>\n";

    foreach my $h (@$hosts) {
      print "  <DEVICE ID=\"H$h->{_name}\">\n";
      print "    <VALUE ID=\"active\">$h->{active_agent}</VALUE>\n";
      print "    <VALUE ID=\"name\">$h->{hostname}</VALUE>\n";
      print "    <VALUE ID=\"ipno\">$h->{ipno}</VALUE>\n";
      print "    <VALUE ID=\"type\">host</VALUE>\n";
      print "    <VALUE ID=\"key\">$h->{hostname}</VALUE>\n";
      print "    <VALUE ID=\"class\">host</VALUE>\n";
      print "  </DEVICE>\n";
    }
  }
 
  print "</DEVICES>\n";
} 

#
# List a given device (an instrumentation report may not be available yet for this device).
#
sub listDevice {
  my($q) = @_;

  my ($type, $key) = split(/\:/, $q->{key});

  my ($renv, $devs, $hosts, $notifs)  = PDM::ConfigFile->read();
  print Client->http_OK();

  my $flag = 0;
  print "<DEVICE_RESULT>\n";
  foreach my $d (@$devs) {
     if ($d->{key} eq $key) {
       print "  <DEVICE ID=\"$d->{_name}\">\n";
       foreach my $el (keys %$d) {
          next if ($el eq "_name");
          print "    <VALUE ID=\"$el\">" . Client->xmlEncode($d->{$el}) . "</VALUE>\n";
       }
       print "  </DEVICE>\n";
       $flag = 1;
     }
  }
  if ($flag == 0) {
    print "<ERROR>Device not found</ERROR>\n";
  }
  print "</DEVICE_RESULT>\n";
}
  
#  turn monitoring on/off on a specific device
#  http://hostname:7654/rashttp?GO=Client::Config::monitorDevice&key=t3:serial_no&monitor=Y|N

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

  my $active = uc($q->{monitor} || "Y");

  my ($type, $key) = split(/\:/, $q->{key});

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

  if ($renv->{hostname} eq $key) {
        $renv->{active_agent} = $active;
        PDM::ConfigFile->write($renv, $devs, $hosts, $notifs) ;
        print "<DEVICE ID=\"MASTER\"</VALUE>\n";
        print "  <VALUE ID=\"active\">$active</VALUE>\n";
        print "  <VALUE ID=\"key\">$renv->{hostname}</VALUE>\n";
        print "  <VALUE ID=\"type\">host</VALUE>\n";
        print "</DEVICE>\n";
        return;
  }

  foreach my $h (@$hosts) {
     if ($h->{hostname} eq $key) {
        $h->{active_agent} = $active;
        PDM::ConfigFile->write($renv, $devs, $hosts, $notifs) ;
        print "<DEVICE ID=\"$h->{_name}\"</VALUE>\n";
        print "  <VALUE ID=\"active\">$active</VALUE>\n";
        print "  <VALUE ID=\"key\">$h->{hostname}</VALUE>\n";
        print "  <VALUE ID=\"type\">host</VALUE>\n";
        print "</DEVICE>\n";
        return;
     }
  }

  foreach my $d (@$devs) {
     if ($d->{key} eq $key) {
        print Client->http_OK();
        $d->{active} = $active;
        PDM::ConfigFile->write($renv, $devs, $hosts, $notifs) ;

        print "<DEVICE ID=\"$d->{_name}\"</VALUE>\n";
        print "  <VALUE ID=\"active\">$active</VALUE>\n";
        print "  <VALUE ID=\"key\">$d->{key}</VALUE>\n";
        print "  <VALUE ID=\"type\">$d->{type}</VALUE>\n";
        print "</DEVICE>\n";
        Events->saveEvent($active eq "Y" ? "QE":"QS", $d->{type}, $d->{key}, "user request, $d->{name}");
        return;
     }
  }

  print Client->error("xml", 301, "Device $q->{key} not found.");
  
  
}

#-----------------------------------------------------------------
# RECOVER THE STORADE CONFIGURATION FROM THE OTHER AGENT
# Client::Config::recoverConfig&alt=boblu10&reset=1
#-----------------------------------------------------------------

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

  print Client->http_OK();

  if (!Util->ping($q->{alt})) {
    print Client->error("xml", 1301, "$q->{alt}");
    return;
  }

  my $file = Util::Http->readFile($q->{alt}, "rasagent.conf");
  if(!$file) {
    print Client->error("xml", 1302, "$q->{alt}");
    return;
  }

  open(O, ">" . System->get_home() . "/DATA/rasagent.conf");
  print O $file;
  close(O);
  my($renv, $devs, $hosts,$notifs) = PDM::ConfigFile->read();
  my $localhost = System->hostname();

  foreach my $h (@$hosts) {
    if ($h->{hostname} eq $localhost) {
      foreach my $x (keys %$h) {
        next if ($x eq "_name");
        my $save = $h->{$x};
        $h->{$x} = $renv->{$x};
        $renv->{$x} = $save;
      }
      last;
    }
  }
  $renv->{hostname} = $localhost;
  
  foreach my $d (@$devs) {
    if ($d->{host} eq $renv->{hostname}) {
      $d->{host} = "";
    }
  }
  PDM::ConfigFile->write( $renv, $devs, $hosts,$notifs);

  if ($q->{reset}) {
    my($renv, $devs, $hosts,$notifs) = PDM::ConfigFile->read();
    my $ip = Util->name2ip($renv->{hostname}) || $renv->{hostname};
    foreach my $h (@$hosts) {
      if ($h->{hostname} ne $renv->{hostname}) {
        my $target = $h->{ipno} || $h->{hostname};
        if (Util->ping($target, 7)) {
          Util::Http->deleteFile($target, "ALTACTIVE");
          Util::Http->saveFile($target, "MASTER", $ip);
        }
      }
    }
  }

  print "<RECOVERCONFIG>$q->{alt}</RECOVERCONFIG> \n";

}

#-----------------------------------------------------------------
# EMAIL THE STORADE CONFIGURATION
# Client::Config::exportConfig&email_address=email&info=comment
#-----------------------------------------------------------------

sub exportConfig {
  my($q) = @_;
  require GUI::DumpConfig;

  print Client->http_OK();
  print "<CONFIG>\n";

  GUI::DumpConfig::dumpConfig1($q);
  print "\n</CONFIG>\n";
  
}

#-----------------------------------------------------------------
# GET THE LIST OF HOSTS
# Client::Config::listHosts?hostId=1.1.2.3
#-----------------------------------------------------------------

sub listHosts {

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

   my(%CNT);

   for ($x=0; $x <= $#$dev; $x++) {
     my $h = $dev->[$x];
     my $hh = $h->{host} || $renv->{hostname};
     $CNT{$hh}++;
   }

   my $hname  = $renv->{hostname};
   my $IPS    = System->ifconfigs();
   my $local_active = "Y";
   my $ip = "";
   my $cnt = 0;
  
   foreach my $i (@$IPS) {
     $ip .= " $i->[1]," if ($i->[1] ne "127.0.0.1");
   }
   chop($ip) if ($ip);
   
   $cnt = $CNT{$hname} + 0;
   my $localId = System->hostid();

  print Client->http_OK();
   
  print "<HOSTS> \n";
   
   if(!$q->{hostID} || $ip eq $q->{hostID}) {
     print "  <HOST> \n";
     print "     <NAME>$hname</NAME> \n";
     print "     <IP>$ip</IP> \n";
     print "     <ACTIVE>$renv->{active}</ACTIVE> \n";
     print "     <ID>$localId</ID> \n";
     print "     <TYPE>M</TYPE> \n";
     print "     <DEVICENUM>$cnt</DEVICENUM> \n"; 
     print "     <FREQUENCY>$renv->{frequency}</FREQUENCY> \n";
     print "     <SKIPLUXADM>$renv->{skip_luxadm}</SKIPLUXADM> \n";
     print "     <CATEGORIES>$renv->{categories}</CATEGORIES> \n";
     print "     <SHOWMONITOREDONLY>$renv->{show_monitored_only}</SHOWMONITOREDONLY> \n";
     print "     <T300LOGFILE>$renv->{t300logfile}</T300LOGFILE> \n";
     print "     <LOGFILE>$renv->{logfile}</LOGFILE> \n";
     print "     <LASTPUSH></LASTPUSH> \n";
     print "     <CONTRACT>".Client->xmlEncode($renv->{contract})."</CONTRACT> \n";
     print "  </HOST> \n";
   }
   
   for ($x=0; $x <= $#$host; $x++) {
     
     my $h = $host->[$x];
     
     #     foreach my $key (keys %$h) {
     #        print " $key   $h->{$key} \n";
     #     }
     
     $cnt = $CNT{$h->{hostname}} + 0;
     
     if(!$q->{hostID} || $h->{ipno} eq $q->{hostID}) {
       
       print "  <HOST> \n";
       print "     <NAME>$h->{hostname}</NAME> \n";
       print "     <IP>$h->{ipno}</IP> \n";
       print "     <ACTIVE>$h->{active}</ACTIVE> \n";
       print "     <ID>$h->{hostid}</ID> \n";
       print "     <TYPE>$h->{role}</TYPE> \n";
       print "     <DEVICENUM>$cnt</DEVICENUM> \n";
       print "     <FREQUENCY>$h->{frequency}</FREQUENCY> \n";
       print "     <SKIPLUXADM>$h->{skip_luxadm}</SKIPLUXADM> \n";
       print "     <CATEGORIES>$h->{categories}</CATEGORIES> \n";
       print "     <SHOWMONITOREDONLY>$h->{show_monitored_only}</SHOWMONITOREDONLY> \n";
       print "     <T300LOGFILE>$h->{t300logfile}</T300LOGFILE> \n";
       print "     <LOGFILE>$h->{logfile}</LOGFILE> \n";
       print "     <LASTPUSH>$h->{last_push}</LASTPUSH> \n"; 
       print "     <CONTRACT>".Client->xmlEncode($h->{contract})."</CONTRACT> \n";
       print "  </HOST> \n";
     } 
   }
   
  print "</HOSTS> \n";
   
}


#-----------------------------------------------------------------
# DELETE SLAVE
# Client::Config::deleteHost?ipno=1.1.1.1
#-----------------------------------------------------------------

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

  my($renv, $dev, $host,$notifs) = PDM::ConfigFile->read();
  
  my $IPS    = System->ifconfigs();
  my $ip = "";
  my $x;
  my $found = 0;
  print Client->http_OK();
  
# check if it is master first
  foreach my $i (@$IPS) {
    $ip .= " $i->[1]," if ($i->[1] ne "127.0.0.1");
  }
  chop($ip) if ($ip);
  if($ip eq $q->{ipno}) {
     print Client->error("xml", 712, "$ip");
     return;
  }

  for ($x=0; $x <= $#$host; $x++) {
     
    if($host->[$x]{ipno} eq $q->{ipno}) {

      my $hostid = $host->[$x]{hostid};
      my $hn = $host->[$x]{hostname};
      unlink(System->get_home() . "/DATA/topo/$hn") if ($hn);
      State->clearComponent("host:$hn");
      $host->[$x]{_name} = "";
      unlink System->get_home() . "/DATA/REMOTE_LISTS/$hn";
      
      my $name = $host->[$x]{hostname} . "/ " . $host->[$x]{ip};
      my $del;
      foreach my $d (@$dev) {
        if ($d->{host} eq $hn) {
          $del++;
          delete $d->{_name};
        }
      }

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

#      &main::log_change($L->expand('deleted',  $name));

      Events->saveEvent("DH", $hn);
       
      $found = 1;

      print "<DELETEHOST>\n";
      print "<VALUE ID=\"$q->{ipno}\">deleted</VALUE>\n";
      print "</DELETEHOST>\n";

      last;
    }
  }

  if($found == 0) {
    print Client->error("xml", 713, "$q->{ipno}");
  } 
}


#-----------------------------------------------------------------
# UPDATE HOST
# Client::Config::updateHost?ipno=1.1.1.1
#-----------------------------------------------------------------
sub updateHost {

  my($q) = @_;
  my($categories) = Agent->findSelectableAgents();
  my ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read;
  my $hname  = $renv->{hostname};
  my $x;
  my $found = 0;
  print Client->http_OK();

  my $IPS    = System->ifconfigs();
  my $local_active = "Y";
  my $ip = "";
  my $cat = "";

  if($q->{allCategories}) {
    foreach my $c (@$categories) {
      my(@bb) = split(/=/, $c);
      $cat .= "$bb[0]|";
    }
  } else {
    foreach my $c (@$categories) {
      my(@bb) = split(/=/, $c);
      $cat .= "$bb[0]|" if ($q->{$bb[0]});
    }
  }

  foreach my $i (@$IPS) {
    $ip .= " $i->[1]," if ($i->[1] ne "127.0.0.1");
  }
  chop($ip) if ($ip);
  if($ip eq $q->{ipno}) {
    #it's a master
    $renv->{frequency} = $q->{frequency};
    $renv->{skip_luxadm} = $q->{skip_luxadm} ? 1:0;
    $renv->{categories} = $cat;
    $renv->{t300logfile} = $q->{t300logfile};
    $renv->{logfile} = $q->{logfile};
    $renv->{contract} = $q->{contract};
    $renv->{show_monitored_only} = $q->{show_monitored_only}? "Y":"N";

    $found = 1;

  } else {
    #check slave
    for ($x=0; $x <= $#$host; $x++) {

     my $h = $host->[$x];

     if($h->{ipno} eq $q->{ipno}) {
#       $h->{hostid} = $q->{hostid};
       $h->{role} = $q->{role}? "AM" : "S";
       $h->{frequency} = $q->{frequency};
       $h->{skip_luxadm} = $q->{skip_luxadm} ? 1:0;
       $h->{categories} = $cat;
       $h->{t300logfile} = $q->{t300logfile};
       $h->{logfile} = $q->{logfile};
       $h->{contract} = $q->{contract};
       $h->{show_monitored_only} = $q->{show_monitored_only}? "Y":"N";

       $found = 1;
       last;
     } 
   }  
  }

  if($found != 1) {
    print Client->error("xml", 710, "$q->{ipno}");        
  } else {
    if (!PDM::ConfigFile->write( $renv, $dev, $host,$notifs)) {
      print Client->error("xml", 709, "$!");        
    } else {
      print "<UPDATEHOST>\n";
      print "<VALUE ID=\"$q->{ipno}\">updated</VALUE>\n";
      print "</UPDATEHOST>\n";
    }
  }
}

#-----------------------------------------------------------------
# ACTIVATE/DEACTIVATE AGENT
# Client::Config::activateHost?ipno=1.1.1.1&active=Y
#-----------------------------------------------------------------

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

  my $IPS    = System->ifconfigs();
  my $ip = "";
  my $x;
  my $found = 0;
  print Client->http_OK();
  
  # check master agent first
  foreach my $i (@$IPS) {
    $ip .= " $i->[1]," if ($i->[1] ne "127.0.0.1");
  }
  chop($ip) if ($ip);

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

  if($ip eq $q->{ipno}) {
    if ($q->{active} eq "Y") {
      $renv->{active} = "Y";

      print "<ACTIVATEHOST>\n";
      print "<VALUE ID=\"$q->{ipno}\">activated</VALUE>\n";
      print "</ACTIVATEHOST>\n";
      
    } elsif ($q->{active} eq "N") {
      $renv->{active} = "N";

      print "<ACTIVATEHOST>\n";
      print "<VALUE ID=\"$q->{ipno}\">deactived</VALUE>\n";
      print "</ACTIVATEHOST>\n";
    }
    PDM::ConfigFile->write( $renv, $dev, $host, $notifs);

    return;
  }
      
  for ($x=0; $x <= $#$host; $x++) {
    if($host->[$x]{ipno} eq $q->{ipno}) {
      if ($q->{active} eq "Y") {
          $host->[$x]->{last_push} = "";
          $host->[$x]->{active} = "Y";
          print "<ACTIVATEHOST>\n";
          print "<VALUE ID=\"$q->{ipno}\">actived</VALUE>\n";
          print "</ACTIVATEHOST>\n";

      } elsif ($q->{active} eq "N") {
          $host->[$x]->{last_push} = "";
          $host->[$x]->{active} = "N";
          print "<ACTIVATEHOST>\n";
          print "<VALUE ID=\"$q->{ipno}\">deactived</VALUE>\n";
          print "</ACTIVATEHOST>\n";
      }
      
      $found = 1;
      PDM::ConfigFile->write( $renv, $dev, $host, $notifs);
      last;
    }
  }

  if($found == 0) {
    print Client->error("xml", 716, "$q->{ipno}");
  }
}

#-----------------------------------------------------------------
# ADD SLAVE
# Client::Config::addHost?hostid=12345&hostname=boblu10
#-----------------------------------------------------------------

sub addHost {
  my($q) = @_;
  my($ho, $o, $err, $cat, $err1);
  my $ipno;

  my($categories) = Agent->findSelectableAgents();
  $q->{hostid} = lc($q->{hostid});

  print Client->http_OK();

  while (1) {
    if ($q->{hostid} eq System->hostid) {
      print Client->error("xml", 701, "$q->{hostid}");
      last;
    } else {
      my $done = 0;
      my $ipno;
      if ($q->{hostname} !~ /^\d+\.\d+\./) {
        my @L = split(/\./, $q->{hostname});
        my $save = $q->{hostname};
        $q->{hostname} = "$L[0]." . lc(System->domain());
        $ipno = Util->name2ip($q->{hostname});
        if (!$ipno) {
          $q->{hostname} = $save;
        } else {
          $done = 1;
        }
      }
      
      if (!$done) {
        $ipno = Util->name2ip($q->{hostname});
        if (!$ipno) {
          print Client->error("xml", 702, "$q->{hostname}");
          last;
        }
      }
      my $sp_info = Util->rasInfo($ipno);

      if ($sp_info->{version} =~ /version\=([\d\.]+)/ && $1 < 2.4) {
        print Client->error("xml", 714, "$sp_info->{version}");
        last;
      }
      if ($sp_info->{solution} =~ /se/) {
        print Client->error("xml", 703, "$sp_info->{solutionModel}");
        last;
      }
      
      if(!$sp_info->{master}){
        # This host doesn't have an active SUNWstade package
        print Client->error("xml", 704, "$q->{hostname}");
        last;
      }
   
      my ($renv, $dev, $host,$notifs) = PDM::ConfigFile->read;
      my %EXIST;
      foreach my $x (@$host) {
        $EXIST{$x->{ipno}}= 1; 
      }
      if ($EXIST{$ipno}) {
        print Client->error("xml", 705, "$ipno");
        last;
      }
      my $x = $#$host + 1;
      $cat = "";

      if($q->{allCategories}) {
        foreach my $c (@$categories) {
          my(@bb) = split(/=/, $c);
          $cat .= "$bb[0]|";
        }
      } else {
        foreach my $c (@$categories) {
          my(@bb) = split(/=/, $c);
          $cat .= "$bb[0]|" if ($q->{$bb[0]});
        }
      }

      my $hostid = $sp_info->{hostid};
      
      if ($hostid ne "Error") {
        $host->[$x]{hostid}   = $hostid;
      } else {
        if ($q->{hostid} !~ /^\w\w\w\w\w\w\w\w$/ && lc(System->os) !~ /linux/) {
          print Client->error("xml", 706, "");
          last;
        }
        $host->[$x]{hostid}   = $q->{hostid};
      }
      if ($sp_info->{master} =~ /=Y/) {
        # convert this master to slave
       
        Util::Http->saveFile($q->{hostname}, "MASTER", $renv->{hostname});

        print Client->error("xml", 707, "$q->{hostname}");
        
      }
      if ($sp_info->{master} =~ /=N/) {  # already a slave
        my $master1 = Util->trim(Util::Http->readFile($ipno, "MASTER", 10));
        if ($master1) {
          my $ip1 = Util->name2ip($master1);
          my $ip2 = Util->name2ip($renv->{hostname});
          if ($ip1 ne $ip2) {
            print Client->error("xml", 708, "$master1");
          }
        }
      }
      
      chop($cat) if ($cat);
      $host->[$x]{categories} = $cat;
      $host->[$x]{_name}    = "host" . ($x+1);
      $host->[$x]{hostname} = $q->{hostname};
      $host->[$x]{ip}       = $q->{hostname};
      $host->[$x]{active}   = "Y";
      $host->[$x]{role}     = $q->{role}? "AM" : "S";
      $host->[$x]{ipno}     = Util->name2ip($q->{hostname});
      $host->[$x]{skip_luxadm} = $q->{skip_luxadm} ? 1:0;

     
      
      $host->[$x]{show_monitored_only} = $q->{show_monitored_only}? "Y":"N";
      $host->[$x]{frequency}= $q->{frequency} || 10;
      $host->[$x]{contract} = $q->{contract} if ($q->{contract});
      $host->[$x]{logfile}  = "/var/adm/messages";

      print $q->{skip_luxadm};
      print $q->{role};
      print $q->{show_monitored_only};

      print $host->[$x]{skip_luxadm};
      print  $host->[$x]{role};
      print $host->[$x]{show_monitored_only};

      my $t3l    = $q->{t300logfile};
      $t3l =~ s/[\n\r]/ /g;
      $host->[$x]{t300logfile} = $t3l;
      #        $q->{ping} =~ s/ *[\|\:\#]+ */#/g;
      #        $q->{ping} =~ s/ *[\n\r]+ */|/g;
#        $host->[$x]{ping}       = $q->{ping};
      
      GUIAdmin->clearSlave($q->{hostname}, $host);
      unlink System->get_home() . "/DATA/snapshot_db";
      Events->saveEvent("AH", $q->{hostid}, $q->{hostname});
      
      Util::Http->saveFile($host->[$x]{ipno}, "MASTER", $renv->{hostname});


      
      if (!PDM::ConfigFile->write( $renv, $dev, $host,$notifs)) {
        print Client->error("xml", 709, "$!");        
      } else {
        #           &main::save_event("AH", $q->{hostid});
        print "<ADDHOST>\n";
        print "<VALUE ID=\"$q->{hostname}\">added</VALUE>\n";
        print "</ADDHOST>\n";
      }
      return;
    }
  }
 
}


#-----------------------------------------------------------------
# UPDATE DEVICE
# (update name and password information)
# Client::Config::updateDevice?key=12345&name=xyz&password=pass
#-----------------------------------------------------------------
sub updateDevice {
  my($q) = @_;

  print Client->http_OK();

  my $key = $q->{key};

  my ($renv, $devs, $host, $notifs) = PDM::ConfigFile->read;
  # look for matching key.
  foreach my $d (@$devs) {
    if ($d->{key} eq $key) {
      $d->{name} = $q->{name};
      if ($q->{password} eq "_BLANK_") {
         $d->{telnet} = "_BLANK_";
      } else {
         require MIME::Base64;
         $d->{telnet} = MIME::Base64::encode($q->{password});
         chomp($d->{telnet});
      }
    }
  }

  PDM::ConfigFile->write($renv, $devs, $host, $notifs);
  print "<STATUS>OK</STATUS>\n";

}

#-----------------------------------------------------------------
#
#-----------------------------------------------------------------
sub decodePassword {
  my($q) = @_;
  print Client->http_OK();
  my $password = System->getDevicePassword({telnet => $q->{password} });
  print $password;
}

sub checkNCPkg {

  print Client->http_OK();
  my $package_base = System->getPackageInfo("", "SUNWnc01", "BASEDIR");
  if (!$package_base) {
    my $t1 = System->getPackageInfo("", "SUNWsrsvp", "_ALL_");
    if (!$t1->{VERSION}) {
      print Client->error("xml", 899, "No Netconnect Pkg Installed");
      return;
    }
  }
  
  print "<PKG>FOUND</PKG> \n";

}

sub getVersion {
  print Client->http_OK();
  my($renv, $devs, $hosts, $notifs) = PDM::ConfigFile->read();
  print $renv->{version};
}

1;
