#!/usr/bin/env perl
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html

# Used as a convience command combined of [nodech]-nodeset-rsetboot-rpower-[rcons/wcons]
# to make ease of node OS provision

# This is the client front-end to rinstall/winstall commands


BEGIN
{
    $::XCATROOT =
      $ENV{'XCATROOT'} ? $ENV{'XCATROOT'}
      : -d '/opt/xcat' ? '/opt/xcat'
      :                  '/usr';
}

use lib "$::XCATROOT/lib/perl";
use File::Basename;
use Getopt::Long;
use xCAT::MsgUtils;
use xCAT::Utils;
use xCAT::Client;
use Cwd;
use strict;

# build a request to go the rinstall plugin
my $bname = basename($0);
my $cmdref;
$cmdref->{command}->[0] = $bname;
$cmdref->{cwd}->[0]     = cwd();

# allows our plugins to get the stdin of the cmd that invoked the plugin
my $data;
if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}))
{
    my $rin = "";
    my $rout;
    vec($rin, fileno(STDIN), 1) = 1;
    my $nfound = select($rout = $rin, "", "", 1);
    if ($nfound)
    {
        while (<STDIN>) { $data .= $_; }
        $cmdref->{stdin}->[0] = $data;
    }
}
else
{
    if (-p STDIN) {
        while (<STDIN>) { $data .= $_; }
        $cmdref->{stdin}->[0] = $data;
    }
}
my $arg;
my @tmpargv = @ARGV;

# first
$arg = shift(@ARGV);

# first  1st non-hyphen arg is the noderange
while ($arg =~ /^-/) {
    push(@{ $cmdref->{arg} }, $arg);
    $arg = shift(@ARGV);
}
$cmdref->{noderange}->[0] = $arg;
push(@{ $cmdref->{arg} }, @ARGV);

my $startconsole=0;
if(grep m/^-c|--console$/,@ARGV){
   $startconsole=1;
}

my $noderange = $cmdref->{noderange}->[0];    # save the noderange

# Allow to print server information when -V/--verbose
foreach (reverse(@ARGV)) {
    if ($_ eq '-V' || $_ eq '--verbose') {
        $ENV{'XCATSHOWSVR'} = 1;
        last;
    }
}

# ok call Client to run the plugin rinstall.pm
xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response);
if ($xCAT::Client::EXITCODE == 0)             # no errors
{
    # if startconsole requested ( -c flag) for rinstall always for winstall
    # This is set in the rinstall plugin
    if ($startconsole == 1) {
        if (basename($0) =~ /rinstall/) {

            exec("rcons $noderange");
        }
        elsif (basename($0) =~ /winstall/) {
            # winstall can commence a wcons command to the noderange for monitoring the provision cycle
            exec("wcons $noderange");
        }
    }
}
exit $xCAT::Client::EXITCODE;
