#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2004,2019 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# sccsid = "@(#)67   1.14   src/rsct/rm/LPRM/cli/bin/lslpcmd.perl, LPRM, rsct_rady, rady2035a 11/12/15 16:38:33"
# Lists resources from the RMC IBM.LPCommands class

use strict;
use locale;
BEGIN
  {
	# this enables us to redirect where it looks for other RSCT files during development
	$::rsctroot = $ENV{'RSCT_ROOT'} || '/opt/rsct';
	$::rsctpm = "$::rsctroot/pm";
	$::rsctmsgmaps = "$::rsctroot/msgmaps";
  }

use lib $::rsctpm;
use Getopt::Std;
use CT_cli_utils qw(printIMsg printEMsg);
use LPRM_cli_utils qw(process_api_error process_exit_code remove_api_error);
use LPRM_cli_include qw($DELIMITERI $DELIMITERO);
use Socket;

$main::PROGNAME = 'lslpcmd';
$main::MSGCAT = 'lprmcli.cat';
#$ENV{MSGMAPPATH} = $::rsctmsgmaps;     # this does not do anything because printIMsg overrides it
$main::LSMSG = '/opt/rsct/bin/ctdspmsg';

# For the usage, see lprmcli.msg
sub usage { printIMsg('IMsgLslpcmdUsageNew2');  exit (scalar(@_) ? $_[0] : 1); }


# Parse the cmd line args and check them
#if (! getopts('Aan:hvV') ) { &usage; }
if (! getopts('Aan:R:hTV') ) { &usage(3); }
#if ((scalar(@ARGV)>0 && $::opt_A) || $::opt_h) { &usage; }
if (scalar(@ARGV)>0 && $::opt_A) { &usage(4); }
if ($::opt_h) { &usage(0); }
if ($::opt_a && $::opt_n) { &usage(5); }
#if ($::opt_V) { $::opt_v = 1; }

my $options = '';
my $selectstr = '';
my $attr = '';
my $longformat = 0;
if ($::opt_A)       # show everything
  {
        if (defined($::opt_R))
           {
            #-R and lpcmdnames cannot be combined
            printEMsg('EMsgLslpcmdImproperFlagUsageCombination');
            exit(5);
           }
	$options = "-I $DELIMITERI -D $DELIMITERO -n -i";
	#$attr = "'*b0x0020'"; to display both p and d
	$attr = "'*p0x0020'"; #display only pers attr 
	$longformat = 1;
  }
elsif (defined($::opt_R)) #show all attrs for this RunCmdName
  {
        if (scalar(@ARGV) >= 1)
           {
            #-R and lpcmdnames cannot be combined
            printEMsg('EMsgLslpcmdImproperFlagUsageCombination');
            exit(5);
           }
	my @runcmdnames = split(/[, ]+/,$::opt_R);
	$options = "-I $DELIMITERI -D $DELIMITERO -n";
	$attr = "'*p0x0020'";
	$selectstr = q/RunCmdName IN ('/ . join("','",@runcmdnames) . q/')/;
	$longformat = 1;
  }
elsif (scalar(@ARGV) >= 1)       # show all attributes of this LP cmd 
  {
	$options = "-I $DELIMITERI -D $DELIMITERO -n";
	#$attr = "'*b0x0020'";
	$attr = "'*p0x0020'";
	$selectstr = q/Name IN ('/ . join("','",@ARGV) . q/')/;
	$longformat = 1;
  }
else           # show all LP command names
  {
	$options = "-i -I $DELIMITERI -D $DELIMITERO";
	$attr = 'Name';
	if ($::opt_a || defined($::opt_n)) { $attr .= "${DELIMITERI}NodeNameList"; }
  }

if ($::opt_a || defined($::opt_n))
  {
	#todo: support symbolic names for values 2 and 3
	if ($ENV{CT_MANAGEMENT_SCOPE}!=2 && $ENV{CT_MANAGEMENT_SCOPE}!=3) { $ENV{CT_MANAGEMENT_SCOPE}=4; }
  }
else { $ENV{CT_MANAGEMENT_SCOPE}=1; }

if (defined($::opt_n))
  {
	my @nodes = split(/[, ]+/,$::opt_n);
	if (length($selectstr)) { $selectstr .= ' && '; }
	$selectstr .= q/NodeNameList IN ('/ . join("','",@nodes) . q/')/;
  }

if (length($selectstr)) { $selectstr = qq("$selectstr"); }

if ($::opt_T) {print STDERR "$main::PROGNAME: calling lsrsrc-api to display LP commands\n ";}

my $cmd = qq(/usr/bin/lsrsrc-api $options -s IBM.LPCommands${DELIMITERI}${selectstr}${DELIMITERI}$attr 2>&1);
#if ($::opt_v) { printIMsg('IMsgRmcCmd', $cmd); }
if ($::opt_V) { printIMsg('IMsgRmcCmd', $cmd); }

my @output = `$cmd`;
#my $rc = $? >> 8;
my $rc = $?;
$rc = process_exit_code($rc);
if ($rc)
  {
	#print $output[0], "\n";
	#if (!$::opt_v) { $output[0] =~ s/.*:\|:.*:\|:.*:\|:.*:\|:.*:\|://; }
        if ($::opt_T) {print STDERR "$main::PROGNAME: lsrsrc-api returned $rc\n ";}
	#if (!$::opt_V) { $output[0] =~ s/.*:\|:.*:\|:.*:\|:.*:\|:.*:\|://; }
        if ($::opt_A && $longformat)
           {
            chop(@output);
            # print errors and remove them from the output
            process_api_error($DELIMITERO,$rc,@output);
            @output = remove_api_error(@output);
            &displayLong;
           }
        elsif ($::opt_a || $::opt_n)
           { 
            # print errors and remove them from the output
            process_api_error($DELIMITERO,$rc,@output);
            @output = remove_api_error(@output);
            goto outputfmt; 
           }
        else
           {
            # print errors 
            process_api_error($DELIMITERO,$rc,@output);
	    #print @output;
           }
	exit $rc;
  }
outputfmt:
chop(@output);
# print errors and remove them from the output
process_api_error($DELIMITERO,$rc,@output);
@output = remove_api_error(@output);
if ($longformat) { &displayLong; }
else
  {
       if (defined($::opt_n) || defined($::opt_a))
          {
           my $size=0;
           foreach my $l (@output)
               {
                my ($name, $node) = split(/$DELIMITERO/, $l);
                if (($name ne "") && ($node ne ""))
                   { 
                   my $new_size=length($name);
                   if ($size < $new_size){$size = $new_size;}
                   }
                else 
                   {print "$name\n";}
               }
           my $colname = "Name";
           my $colnodeName = "NodeName";
           printf "%-${size}s\t%s\n", $colname, $colnodeName;
           foreach my $l (@output)
            {
                my ($name, $node) = split(/$DELIMITERO/, $l);
                if (($name ne "") && ($node ne ""))
                   {  printf "%-${size}s\t%s\n", $name, $node;}
            }
           exit;
          }

	foreach my $l (@output)
	  {
		my ($name, $node) = split(/$DELIMITERO/, $l);
		if (length($node)) { $node = "   $node"; }
		print $name, $node, "\n";
	  }
  }
#if (!scalar(@output)) { print "\n"; }

exit;


sub displayLong
  {
	my $firsttime = 1;
	foreach my $l (@output)
	  {
		if (!$firsttime) { print "-------------------\n"; }   # separate this resource from the previous
		else { $firsttime = 0; }

		# takes the alternating attrs and values and puts them in the hash correctly
		my %attrs = split(/$DELIMITERO/, $l);

		# Make sure the hostname is displayed 1st
		if (defined($attrs{Name}))
		  {
			print " Name = $attrs{Name}\n";
			delete $attrs{Name};          # so we do not repeat it in the following loop
		  }

		# Now display the rest of the attributes, sorted
		foreach my $k (sort keys %attrs)
		  {	
                   #defect 116818, when one of the rsrcs is in error, even if user specified -A the output format was messed up. $l=$k in error scenarios
                   if ($l eq $k) {print " $k\n";} 
                   else {print " $k = $attrs{$k}\n";} 
                  }
	  }
  }