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

# Used as a standard client cmd that can be used for many of the xcat cmds.
# It grabs the arguments, noderange, and stdin and then submits the request to
# xcatd and waits for responses.  Most of the client/server communication is
# contained in Client.pm.

# To use this, sym link your cmd name to this script.

BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; }
use lib "$::XCATROOT/lib/perl";
use Cwd;
#use IO::Socket::SSL;
#use IO::Socket::INET;
use File::Basename;
#use Data::Dumper;
use xCAT::Client;

my $bname = basename($0);
my $cmdref;
if ($bname =~ /xcatclient/) { $cmdref->{command}->[0]=shift @ARGV; }  # xcatclient was invoked directly and the 1st arg is cmd name that is used to locate the plugin
else { $cmdref->{command}->[0] = $bname; }        # the cmd was sym linked to xcatclient
$cmdref->{cwd}->[0] = cwd();

if (-p STDIN) {
  my $data;
  while ( <STDIN> ) { $data.=$_; }
  $cmdref->{stdin}->[0]=$data;
}

# Consider the 1st non-hyphen arg to be the noderange.  All others (before and after) go on the arg list.
my $arg=shift(@ARGV);
while ($arg =~ /^-/) {
  push (@{$cmdref->{arg}}, $arg);
  $arg=shift(@ARGV);
}
if ($arg ne "NO_NODE_RANGE") {
  # The noderange can be specified through a noderange file,
  # the noderange file can be a relative path,
  # convert the relative path to a full path.
  # an ideal way is converting the relative path in xCAT::Noderange::noderange,
  # but the existing xCAT::Noderange::noderange can not get the cwd(),
  # needs to change all the callers to pass the cwd(),
  # there are more than 100 callers.
  my @tempnr = ();
  foreach my $nr (split(/,/, $arg)) {
    if ($nr =~ /^\^(.*)$/) {
      my $nrf = $1;
      if ($nrf !~ /^\//) { #relative path
        $nrf = Cwd::abs_path($nrf);
      }
      $nrf = "\^" . $nrf;
      push @tempnr, $nrf;
    } else {
      push @tempnr, $nr;
    }
  }
  $arg = join(',',@tempnr);
  $cmdref->{noderange}->[0]=$arg;
}
push (@{$cmdref->{arg}}, @ARGV);

xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response);
exit $xCAT::Client::EXITCODE;