#!/usr/bin/perl -I/opt/SUNWstade/lib
use System;
use Service::Array;
use Getopt::Std;
use strict;
use Process;
use vars qw(%opts $ip $pass $WAIT_TIME $WAIT_TRY $ID $cpid);

#
# run boot -w on the array of your choice
#
# START:
# WAIT: or ERROR:
# DONE1:
# DONE2:
#

if (!getopts("i:p:", \%opts) || !$opts{i}) {
    print " array_boot -i [ip] -p [password] \n";
    exit(0);
}

if (($cpid = fork()) == 0) {
  close STDIN; 
  close STDOUT; 
  close STDERR;
} else {
  exit;
}


System->set_home("/opt/SUNWstade");
my($renv) = PDM::ConfigFile->read();
System->get_renv($renv);


$ID        = "array_boot";
$WAIT_TIME = 60;
$WAIT_TRY  = 20;
$ip        = $opts{i};
$pass      = $opts{p};

Process->start($ID);

&log1("START: Starting -w on $ip.");

my($error, $info) = Service::Array->boot_w($ip, $pass);

if ($error) {
  &log1("ERROR",$error);
  Process->done($ID);
  exit(1);

} else {
  &log1("DONE1", "Device is rebooting");
}

my $try;
while (1) {
   sleep $WAIT_TIME;
   if (!Service::Array->openArrayConnection($ip, "")) {
      $try++;
      if ($try > $WAIT_TRY) {
         &log1("ERROR","$ip is not accessible after $try minutes.");
         Process->done($ID);
         exit(1);
      } else {
         &log1("WAIT","Waited $try minute(s) for $ip to come up.");
      }
   } else {
      Service::Array->closeArrayConnection();
      last;
   }
}

&log1("DONE2","$ip is now available!");

Process->done($ID);


sub log1 {
  my($status, $mess) = @_;

  my $report = { date => Util->get_today()  , 
                 data => { trace => $mess, status => $status } , 
               };

  Process->write($report, $ID);
}

