#!/usr/bin/perl -I/opt/SUNWstade/lib

# 
# currently only works on the master.
#
use strict 'vars';
use System;
use Util::Http;
use Util;
use Getopt::Std;
use PDM::ConfigFile;
use Data::Dumper;

my $local_p   = $INC[0];
my($ix)    = rindex($local_p, "/");
my(%opts);

my $HOME      = substr($local_p,0,$ix);

System->set_home($HOME);
my $RASPORT   = System->getConfigPort($HOME);
System->set_rasport($RASPORT);

my $MASTER    = Util->findMaster();

my $COMMANDS  = ",site_info,host_list,host_detail,device_list,device_detail," .
             "email_list,site_info_upd,agent,review_config,t3_add,switch_add,".
             "discover_subnet,discover_solution,login_add,login_delete,login_update,login_list," . 
             "host_delete,push_config,report_list,report,provider_on,provider_off,alert_list," . 
             "event_list,device_delete_all,topo_list,topo,provider_list,";

sub usage {
  print "
 Usage   : ras_admin command [options]
 Commands:
  site_info      : get site information.
  host_list      : List of hosts.
  host_detail    : details about host(s).
  host_delete    : delete a host from the config .
  device_list    : list of devices.
  device_detail  : details about device(s).
  device_delete_all: Delete all devices.
  email_list     : list email set for notifications.
  site_info_upd  : Update Site Information.
  agent          : Start/Stop agent.
  review_config  : Review the configuration.
  t3_add         : Add a t3 to the config if valid.
  switch_add     : Add a Sun Switch to the config if valid.
  discover_subnet: find t3 and switches on the subnet.
  discover_solution: add 3900/6900 from Golden snapshot.
  discover_switch: discover switches entered in /etc/fcswitch. 
  login_list     : list all logins.
  login_add      : add new login.
  login_delete   : delete a login.
  login_update   : update password or roles of a login.
  push_config    : Update Slave configuration.
  report_list    : list all available instrumentation reports.
  report         : display one report.
  provider_list  : List status of providers.
  provider_on    : turn/on notification provider.
  provider_off   : turn/off notification provider.
  alert_list     : Show current alerts (warnings/errors).
  topo_list      : List of Topologies.
  topo           : Display a topology.
  \n\n";
}
#  event_list     : Show X most recent alerts.

my $command = shift @ARGV;

if ($command eq "help" || $command eq "usage") {
   &usage();
   exit;
}

if (index($COMMANDS, ",$command,") < 0) {
   &usage();
   exit;
}
my($renv, $devices, $hosts, $notifs) = PDM::ConfigFile->read();
System->set_renv($renv);

&$command();
print "\n";
exit(0);

use Roles;

sub login_list {
  if (!getopts("?", \%opts) || $opts{'?'} ) {
     print "Usage: ras_admin login_list [-?] \n";
  }
  my $db = Roles->read();
  my $list = $db->userList();
  my $f = "%-20.20s %-20.20s %-30.30s\n";

  printf($f, "Login","Name","Roles");
  printf($f, &lines(3));
  foreach my $e (@$list) {
    printf($f, $e->{user}, $e->{name}, $e->{roles});
  }
}



sub login_add {
  if (!getopts("l:p:r:?", \%opts) || $opts{'?'} || !$opts{l} || !$opts{p} ) {
     print "Usage: ras_admin login_add -l login -p password -r role1:role2.. [-?] \n";
     print "       Roles: user|admin|script|test \n";
     exit(1);
  }
  my $role;
  foreach my $e (split(/\:/, $opts{r}))  {
     if (index(",user,admin,script,test,", ",$e,") < 0) {
        print "Invalid role: $e \n";
        exit(1);
     }
     $role .= "$e|";
  }
  chop($role) if ($role);
  my $db = Roles->read();
  $db->addUser($opts{l}, $opts{l}, $opts{p}, $role);
  $db->write();
}

sub login_delete {
  if (!getopts("l:?", \%opts) || $opts{'?'} || !$opts{l}) {
     print "Usage: ras_admin login_delete -l login  [-?] \n";
     exit(1);
  }
  my $login = $opts{l};
  my $db = Roles->read();
  if ($login ne "storade") {
    $db->deleteUser($login);
    $db->write();
  }
}

sub login_update {
  if (!getopts("l:p:r:?", \%opts) || $opts{'?'} || !$opts{l}) {
     print "Usage: ras_admin login_update -l login -p password -r role1:role2 [-?] \n";
     print "       Roles: user|admin|script|test \n";
     exit(1);
  }
  my $role;
  foreach my $e (split(/\:/, $opts{r})) {
     if (index(",user,admin,script,test,", ",$e,") < 0) {
        print "Invalid role: $e \n";
        exit(1);
     }
     $role .= "$e|";
  }
  chop($role) if ($role);
  my $db = Roles->read();
  my $user = $db->getUser($opts{l});
  if ($user) {
     $user->{roles}  = $role if ($role);
     $user->{password} = Roles->encode($opts{p}) if ($opts{p});
     $db->write();
  } else {
     print "Cannot find $opts{l} \n";
     exit(1);
  }
}

sub push_config {
  if (!getopts("h:?", \%opts) || $opts{'?'} || !$opts{h} ) {
     print "Usage: ras_admin push_config -h hostname|ALL [-?] \n";
     exit(1);
  }
  require Logic::Slave;

  foreach my $h (@$hosts) { 
    if (lc($h->{hostname}) eq lc($opts{h}) || $opts{h} eq "ALL") {
        my $rc = Logic::Slave->push($h) ;
        print substr($rc,3) if ($rc);
    }
  }
}

sub topo {
  if (!getopts("?t:", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin topo -t topo_name [-?] \n";
     print "Example: ras_admin topo MERGE-MASTER \n";
     exit(1);
  }
  require TO;
  my $to = TO->readExistingTopo($opts{t});
  print $to->toC();
}

sub topo_list {
  if (!getopts("?h:", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin topo_list [-?] \n";
     exit(1);
  }
  my $D = System->get_home() . "/DATA/topo";
  opendir(O, $D);
  my @topos = readdir(O); closedir(O);

  my $f = "%-30.30s %s\n";
  printf($f, "Name","Date");
  printf($f, &lines(2));
  foreach my $topo (@topos) {
    next if (substr($topo,0,1) eq ".");
    my $created = Util->get_file_created("$D/$topo");
    printf($f, $topo, $created);
  }
  print "Done.\n";
}

sub report_list {
  if (!getopts("?h:", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin report_list -h host [-?] \n";
     exit(1);
  }
  require Report;
  my $list = Report->reportList();
  my $f = "%-10.10s %-25.25s %-20.20s %s\n";

  printf($f, "Type","Host","Name/Device", "ReportKey");
  printf($f, &lines(4));

  my $list = Report->reportList();

  my $cnt;
  foreach my $key (sort keys %$list) {
     my $v = $list->{$key};
     next if ($opts{h} && lc($opts{h}) ne $v->[0]);
     printf($f, $v->[1], $v->[0], $v->[4], $key);
     $cnt++;
  }
  print "Count: $cnt\n";
}

sub report {
  if (!getopts("?k:h:", \%opts) || $opts{'?'} || !$opts{k}) {
     print "Usage: ras_admin report -k reportKey -h host [-?] \n";
     exit(1);
  }
  require Report;
  my ($err, $report) = Report->readReport($opts{k}, $opts{h});
  if ($err) {
     print "ERROR: $err \n";
     exit(1);
  }
  print $report->toString({summary => 1});
}

sub provider_list {
  my $f = "%-10.10s %-6.6s %-15.15s %-20s\n";
  printf($f, "Provider","Active", "Heartbeat (hrs)", "IP");
  printf($f, &lines(4));
  
  foreach my $p ('sunmc','ssrr','srs','netconnect','http','nscc_email') {
     my $act = $renv->{"pro.$p.active"} || "N";
     $act = "  $act";
     printf($f, $p, $act,
                $renv->{"pro.$p.frequency"},
                $renv->{"pro.$p.ip"},
           );
  }
  print "Done.\n";
}

sub provider_on {
  &set_provider('Y');
}

sub provider_off {
  &set_provider('N');
}

sub provider_usage {
  my($flag) = @_;
  my $l = $flag eq 'Y' ? "provider_on" : "provider_off";
  print "Usage: ras_admin $l -p sunmc|ssrr|srs|netconnect|http|nscc_email -f frequency -i ipaddr [-?] \n";
  exit(1);
}
  

sub set_provider {
  my( $flag) = @_;
  $opts{p} = lc($opts{p});
  if (!getopts("p:?f:i:", \%opts) || $opts{'?'}  ||
         index(",sunmc,ssrr,srs,netconnect,http,nscc_email,", ",$opts{p},") < 0) {
     &provider_usage($flag);

  }
  # formerly rss
  if ($opts{p} eq "ssrr") {
     $renv->{'pro.ssrr.active'} = $flag;
     $renv->{'pro.ssrr.frequency'}  = ($opts{f} + 0) || 6;
     
     PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);

  } elsif ($opts{p} eq "srs") {
     my $ip = $opts{i};
     &provider_usage($flag) if (!$ip);
     $renv->{'pro.srs.active'}     = $flag;
     $renv->{'pro.srs.frequency'}  = ($opts{f} + 0) || 6;
     $renv->{'pro.srs.ip'}         = $ip;
     PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);

  } elsif ($opts{p} eq "sunmc") {
     my $ip = $opts{i};
     &provider_usage($flag) if (!$ip);
     $renv->{'pro.sunmc.active'}     = $flag;
     $renv->{'pro.sunmc.frequency'}  = ($opts{f} + 0) || 6;
     $renv->{'pro.sunmc.ip'}         = $ip;
     PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);

  } elsif ($opts{p} eq "netconnect") {
     $renv->{'pro.netconnect.active'}     = $flag;
     $renv->{'pro.netconnect.max'}        = 2000;
     PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);

  } elsif ($opts{p} eq "http") {
     $renv->{'pro.http.active'}     = $flag;
     PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);

  } elsif ($opts{p} eq "nscc_email") {
     $renv->{'pro.nscc_email.active'}     = $flag;
     PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);
  }
  print "$opts{p} is " . ($flag eq "Y" ? "on" : "off") . "!\n";

}

sub event_list {
  if (!getopts("?h:", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin event_list -h host [-?] \n";
     exit(1);
  }
  print "not yet\n";
}



sub alert_list {
  require State;
  my $list = State->getStateList();
  my $f = "%-7.7s %-5.5s %-20s %-20s %-40s\n";
  my @S = ('Normal','Warning','Errors','Down');
  my %T = ('C' => 'Comp.', L => 'Link');

  printf($f, "Sev","Comp","Device1", "Device2", "Name");
  printf($f, &lines(5));
  foreach my $sev (3,2,1) {
    foreach my $l (@$list) {
      if ($l->[1] == $sev) {
         my $name;
         if ($l->[0] eq 'C') {
           $name = "Name    : $l->[5]";
         } else {
           $name = "Device2 : $l->[3]";
         }
         my $x = 0;
         my $desc;
         my $d = $l->[4];
         while (length($d) > 0) {
            $desc .= substr($d,0,60);
            $d = substr($d,60);
            $desc .= "\n        : " if (length($d) > 0);
         }
         print <<EOF;
Severity: $S[$l->[1]] 
Type    : $T{$l->[0]}
Device1 : $l->[2]
$name
Descrip.: $desc

EOF
      }
    }
  }
}

sub site_info() {
    
  if (!getopts("?", \%opts) || $opts{'?'} ) {
     print "Usage: ras_admin site_info [-?] \n";
     exit(1);
  }

  print <<EOF;
Customer  : $renv->{customer} 
Contract  : $renv->{contract},  CustNo : $renv->{cust_no} 
Address   : $renv->{site_address}, $renv->{site_city}
          : $renv->{site_state}, $renv->{site_zip}, $renv->{site_country}
Contact   : $renv->{site_contact}, Phone: $renv->{site_contact_phone}
Email     : $renv->{site_email}
Production: $renv->{production}

EOF
}

sub host_list {
  if (!getopts("?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin host_list [-?] \n";
     exit(1);
  }
  my ($x, @X) ;
  $hosts = &sort($hosts, "hostname");
  &push_master($hosts, $renv);

  my $f = "%-25.25s %-25.25s %-6.6s %-4.4s %-10.10s %-5.5s\n";

  printf($f, "Hostname","IP","Active","Role", "SE-Model", "Freq.");
  printf($f, &lines(6));
  
  foreach my $h (@$hosts) {
     printf($f, $h->{hostname}, $h->{ipno}||$h->{ip}, $h->{active}, 
            $h->{role}, 
            $h->{solution_model},
            $h->{frequency}, 
            );
  }
  
}

# delete only slaves

sub host_delete {
  if (!getopts("n:d?", \%opts) || $opts{'?'} || !$opts{n} ) {
     print "Usage: ras_admin host_delete -n hostname -d [-?]\n";
     print " -d : delete devices\n";
     exit(1);
  }
  my $x;
  my $name = lc($opts{n});
  my $found;
  for ($x=0; $x <= $#$hosts; $x++) {
     my $h = $hosts->[$x];
     if ($name eq lc($h->{hostname}) ) {
        $hosts->[$x] = {};
        $found = 1;
     }
  }
  if ($found) {
      print "$name deleted.\n";
  } else {
      print "$name not found.\n";
  }
  my $cnt = 0;
  if ($opts{d}) {
     for ($x=0; $x <= $#$devices; $x++) {
         my $dev = $devices->[$x];
         my $h = $dev->{host} || $renv->{hostname};
         if (lc($h) eq $name) {
             $devices->[$x] = {}; $cnt++;
         }
    } 
  } 
  print "$cnt devices deleted.\n";
  PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);
}



sub host_detail {
  if (!getopts("n:i:?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin host_detail -n hostname -i ip [-?] \n";
     exit(1);
  }
  my $name = lc($opts{n});
  my $ip   = lc($opts{i});
  &push_master($hosts, $renv);
  foreach my $h (@$hosts) {
     next if ($name && lc($h->{hostname}) !~ /^$name/);
     next if ($ip && lc($h->{ipno}) !~ /^$ip/);
     print <<EOF;
------------------------------------------
Hostname   : $h->{hostname}
Hostid     : $h->{hostid}
IP         : $h->{ipno}
Role       : $h->{role}
SE-Model   : $h->{solution} / $h->{solution_model}
Categories : $h->{categories}
Frequency  : $h->{frequency}
Logfile    : $h->{logfile}
T3Logfile  : $h->{t300logfile}
InBand Mon.: $h->{datahost}
EOF
  }
}

sub device_list {
  if (!getopts("s:h:?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin device_list -s sort -h host [-?] \n";
     print " Sort  : type | host | name \n";
     print " Filter: show devices monitored by this host only \n";
     exit(1);
  }
  if ($opts{s} && index("type,host,name", $opts{s}) < 0) {
     print "Error: Invalid sort name \n";
     exit(1);
  }

  my $f = "%-20.20s %-18.18s %-10.10s %-16.16s %-18.18s %-6.6s\n";
  my $host  = lc($opts{h});

  printf($f, "MonitoredOn","Device","Type","IP", "WWN", "Active");
  printf($f, &lines(6));
  foreach my $d (@$devices) {
     $d->{host} = $renv->{hostname} if (!$d->{host});
     next if ($host && lc($d->{host}) !~ /^$host/);
     printf($f, 
            $d->{host},
            $d->{name}, 
            $d->{type}, 
            $d->{ipno},
            $d->{wwn}, 
            $d->{active}
            );
  }
}

sub device_detail {
  if (!getopts("h:n:i:t:?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin host_detail -h host -n devicename -i ip -t type [-?] \n";
     exit(1);
  }
  my $host = lc($opts{h});
  my $name = lc($opts{n});
  my $ip   = lc($opts{i});

  foreach my $d (@$devices) {
     my $found = 0;
     $d->{host} = $renv->{hostname} if (!$d->{host});
     next if ($host && lc($d->{host})  !~ /^$host/);
     next if ($name && lc($d->{name})  !~ /^$name/);
     next if ($ip &&   lc($d->{ipno})  !~ /^$ip/);

     print <<EOF;
------------------------------------------
DeviceName : $d->{name}
Type       : $d->{type}
Ip         : $d->{ipno}
MonitoredOn: $d->{host}
Key        : $d->{key}
Active     : $d->{active}
Wwn        : $d->{wwn}
EOF
     foreach my $el (sort keys %$d) {
       next if (substr($el,0,1) eq "_" || $el eq "class");
       if (index(",name,host,type,ipno,key,active,wwn,", $el) < 0 && $d->{$el}) {
           printf "%-11.11s: %s\n", ucfirst($el), $d->{$el};
       }
     }
  }
}


sub device_delete_all {
  if (!getopts("?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin device_delete_all [-?]\n";
     exit(0);
  }
  my $x;
  for ($x=0; $x <= $#$devices; $x++) {
     $devices->[$x]{_name} = "";
  }
  PDM::ConfigFile->write($renv, $devices, $hosts, $notifs);
  print "All devices deleted!\n";
}

  

  
sub email_list {
  if (!getopts("?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin email_list [-?] \n";
     exit(1);
  }
  my ($x, @X) ;

  my $f = "%-30.30s %-10.10s %-10.10s %-10.10s %-10.10s\n";
  printf $f, "Email/Events", "Type", "Device", "Priority", "Events";
  printf $f, &lines(5);

  foreach my $n (@$notifs) {
     my $dev = $n->{device} eq "*" ? "All" : $n->{device};
     my $prio= $n->{priority} eq "*" ? "All" : $n->{priority};
     my $ev;
     if ($n->{event} eq "*") {
         $ev = "All";
     } else {
       my @E = split(/\|/, $n->{event});
       $ev = $#E + 1;
     }
     printf $f , $n->{email}, $n->{type}, $dev, $prio, $ev;
     print "     " . $n->{event} . "\n" if ($n->{event} ne "*");
     print "     Run:" . $n->{script} . "\n" if ($n->{script});
  }
}

sub site_info_upd {
  if (!getopts("e:n:i?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin site_info_upd  -e new_email -n new_name -i interactive [-?] \n";
     exit(1);
  }
  my $upd = 0;
  if ($opts{e}) {
     $renv->{site_email} = $opts{e};
     $upd = 1;
  }
  if ($opts{n}) {
     $renv->{customer} = $opts{n};
     $upd = 1;
  }
  if ($opts{i} || !$upd) {
     print "\n";
     $upd = &enter($renv, "customer*,contract,cust_no,site_name*,site_address*,site_city*,site_state*,site_zip*,site_country*," .
            "site_contact*,site_contact_phone,site_email");
  }
  PDM::ConfigFile->write($renv, $devices, $hosts, $notifs) if ($upd);
}


sub agent {
  if (!getopts("sph:?", \%opts) || $opts{'?'} || (!$opts{s} && !$opts{p}) ) {
     print "  Usage: ras_admin agent [-s|-p]  -h host [-?] \n";
     print "    -s : Start\n";
     print "    -p : Stop \n";
     print "Example: ras_admin agent -s -h host1 \n";
     exit(1);
  }
  if (!$opts{h}) {
     my $F = System->get_home() . "/DATA/start";
     if ($opts{s}) {
        open(O, ">$F"); print O "\n"; close(O);
        print "Agent started!\n";
     } else {
        unlink $F;
        print "Agent stopped!\n";
     }
     return;
  }
  my $host;
  if (!($host = findHost($opts{h}) )) {
     print "Error: Host $opts{h} does not exist!\n";
     return;
  }
  if ($opts{s}) {
     my $rc =  Util::Http->getCommand($host, "CREAT&file=start", 10);
     print $rc . "\n";
  } else {
     my $rc =  Util::Http->getCommand($host, "DELET&file=start", 10);
     print $rc . "\n";
  }
}

sub review_config {
  if (!getopts("?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin review_config [-?] \n";
     exit(1);
  }
  require GUI::Review;
  my $L = GUI::Review::run_();
  my $cnt=1;
  foreach my $el (@$L) {
    $el =~ s/<a href=[^>]+>//;
    $el =~ s/<\/*font[^>]*>//g;
    $el =~ s/<[\/abrp]+>//g;
    printf "%3.3d. %s\n\n",  $cnt, $el;
    $cnt++;
  }
  if ($#$L < 0) {
     print "No error found in configfile!\n";
  }

}

#######
# T3
#######

sub t3_add {
  if (!getopts("n:i:h:p:?", \%opts) || $opts{'?'} || !$opts{n} || !$opts{i} ) {
     print "Usage: ras_admin t3_add -n name -i ip -h host -p password [-?] \n";
     exit(1);
  }
  if ($opts{h} && !findHost($opts{h}) ) {
    print "Invalid Hosname! \n";
    return;
  }
  require Logic::T3;
  my ($err, $dev) = Logic::T3->addToConfig(
          { name => $opts{n},
              ip => $opts{i},
            host => $opts{h},
           telnet=> $opts{p},
          });
  if ($err) {
     print $err->toString() . "\n";
  } elsif ($dev) {
     print "Device $opts{n} added ! \n";
     print Dumper($dev);
  } else {
     print "Unknown error \n";
  }
}

##########
# SWITCH
##########


sub switch_add {
  if (!getopts("n:i:h:?", \%opts) || $opts{'?'} || !$opts{n} || !$opts{i} ) {
     print "Usage: ras_admin switch_add -n name -i ip -h host [-?] \n";
     exit(1);
  }
  if ($opts{h} && !findHost($opts{h}) ) {
    print "Invalid Hosname! \n";
    return;
  }
  require Logic::SWITCH;
  my ($err, $nodes) = Logic::SWITCH->addToConfig(
          { name => $opts{n},
              ip => $opts{i},
            host => $opts{h},
          });

  if ($err) {
     print $err->toString() . "\n";

  } elsif ($#$nodes >= 0) {
     print "" . ($#$nodes + 1) . " device(s) added! \n";
     foreach my $d (@$nodes) {
        print Dumper($d);
     }
  } else {
     print "Unknown error \n";
  }
}

###############
#  SOLUTION
###############

sub discover_solution {
  require Logic::Solution;
  if (!getopts("h:?", \%opts) || $opts{'?'}) {
     print "Usage: ras_admin discover_solution -h host [-?] \n";
     exit(1);
  }
  my ($err, $nodes, $info) = Logic::Solution->addToConfig( { host => $opts{h},monitor_on => "Y" });
  if ($err) {
    print $err->toString();
    exit(1);

  } elsif ($#$nodes >= 0) {
     print "found " . ($#$nodes+1) . " devices. \n";
     my $F = "%-10.10s %-20.20s %-20.20s\n";
     printf ($F , "Type", "Name", "Key");
     printf ($F , &lines(3));
     foreach my $d (@$nodes) {
       printf ($F,$d->{type}, $d->{name} , $d->{key});
     }
  }
}

###############
#  SUBNET
###############


sub discover_subnet {
  require Logic::Subnet;

  if (!getopts("h:s:ap:m?", \%opts) || $opts{'?'} || !$opts{s}) {
     print "Usage: ras_admin discover_subnet -h host -s subnet -a -p prefix -m [-?] \n";
     print "   -a: Use hostname as prefix\n";
     print "   -m: monitoring off\n";
     exit(1);
  }
  my $mon = 1 if (!$opts{m});
  my ($err, $nodes, $info) = Logic::Subnet->addToConfig(
          { host => $opts{h},
            SUB1  => $opts{s},
            prefixT => $opts{a},
            prefix  => $opts{p},
            monitor_on => $mon,
          });
  print $info;
  if ($err) {
     print $err->toString() . "\n";
  } elsif ($#$nodes >= 0) {
     print "found " . ($#$nodes+1) . " devices \n";
  }

}

sub discover_switch {
  if (!getopts("f:?", \%opts) || $opts{'?'} || !$opts{s}) {
     print "Usage: ras_admin discover_switch  -f filename [-?] \n";
     exit(1);
  }
  my ($err, $nodes, $info) = Logic::Subnet->addFromFile( { file  => $opts{f} } );
  if ($err) {
    print $err->toString() . "\n";
  } else {
    print "$info\n" if ($info);
  }
}
  

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

sub findHost {
  my($host) = @_;
  foreach my $h (@$hosts) {
      if (lc($h->{hostname}) eq lc($host)) {
         return $h->{hostname};
      }
  }
  return undef;
}

sub enter {
  my($renv, $l) = @_;
  my @E = split(/,/, $l);
  my $width = 0;
  foreach my $el (@E) {
     $width = length($el) if (length($el) > $width);
  }
  $width += 7;
  my (%q, $ans);
  while (1) {
    foreach my $el (@E) {
       my $label = ucfirst($el); $label =~ s/_/ /g;
       my $mand;
       if (substr($label,-1) eq "*") {
          $mand = 1 ; chop($el);
       }
       while (1) {
         printf("%-${width}s: ",  "Enter $label");
         $ans = <STDIN>; chop($ans);
         last if ($ans || !$mand);
       }
       $q{$el} = $ans;
    }
    print "\n------ You entered ------ \n";
    foreach my $el (@E) {
       printf("%-${width}s: %s\n", ucfirst($el), $q{$el});
    }
    print "Do you want to save these values [y=yes, n=no, q=quit]: ";
    my $yn = <STDIN>;
    chop($yn);
    return undef if (lc($yn) eq "q");
    last if (lc($yn) eq "y");
  }
  foreach my $el (keys %q) {
     $renv->{$el} = $q{$el};
  }
  return 1;
}

sub sort {
   my($h, $key) = @_;
   my (@X, $x, @NEW);
   for ($x=0; $x <= $#$h; $x++)  {
      my $el = $h->[$x];
      push(@X, "$el->{$key} | $x");
   }
   foreach my $el (sort @X) {
       my($v, $ix) = split(/ \| /, $el);
       push(@NEW, $h->[$ix]);
   }
   return \@NEW;
}
         

sub lines {
  my ($cnt) = @_;
  my (@L, $x);
  for ($x=1; $x <= $cnt; $x++) {
     push(@L, "-------------------------------");
  }
  return @L;
}


sub push_master {
  my($hosts, $renv) = @_;
  my %H;
  foreach my $el ('active','categories','frequency','hostid','hostname','ip','ipno','logfile',
         'role','solution','solution_model') {
     $H{$el} = $renv->{$el};
  }
  $H{role} = 'M';
  unshift(@$hosts, \%H);
}

