#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2000,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 = "@(#)27   1.22   src/rsct/rm/SensorRM/cli/bin/chsensor.perl, sensorcli, rsct_rady, rady2035a 11/12/15 16:37:19"

# Changes 1 or more attributes of a resource from the RMC IBM.Sensor 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::Long;
use CT_cli_utils qw(printIMsg printEMsg);
use CT_cli_input_utils qw(
    check_input_file
);
use MC_cli_utils qw(
     read_from_Stdin
);

$main::PROGNAME = 'chsensor';
$main::MSGCAT = 'sensorcli.cat';
$main::LSMSG = '/opt/rsct/bin/ctdspmsg';

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

Getopt::Long::Configure ("bundling", "no_auto_abbrev",
                         "no_ignore_case", "require_order",
                         "prefix_pattern=(--|-)");
# Parse the cmd line args and check them
if(!GetOptions( 'h|help|version',  # --help , --version, --h, -h
                'a',
                'm',
                'v',
                'V',
                'i=s',
                'n=s',
                'N=s' ))
{
    &usage;
}
if ($::opt_h) { &usage(0); }
if (scalar(@ARGV) < 1 || 
    (scalar(@ARGV) == 1 && !defined($::opt_i)) ||
    (defined($::opt_n) && defined($::opt_N)) ||
    ($::opt_a && defined($::opt_n)) ||
    ($::opt_a && defined($::opt_N)) ) 
{ 
   &usage;
}

# set -api command delimiters
my $DELIMITERI = "tvitvitvi";
my $DELIMITERO = "tvotvotvo";

if ($::opt_V) { $::opt_v = 1; }

# determine the class to use
my $CLASSNAME = "IBM.Sensor";
if ($::opt_m) { $CLASSNAME = "IBM.MicroSensor"; }

if (defined($::opt_i))
   {
     if (scalar(@ARGV) < 2)
        {
         $::opt_i = "RefreshInterval${DELIMITERI}$::opt_i";
        }
     else
       { 
         $::opt_i = "${DELIMITERI}RefreshInterval${DELIMITERI}$::opt_i";
       }
    }
my $name = shift @ARGV;
my $selectstr = "Name='$name'";
my $node_file_flag = 0;                           # node_file_flag =1         if -N was specified.
my $node_file_name = "";                          # node_file_name
my $node_file_from_stdin = 0;                     # node_file_from_stdin = 1  if -N '-' 

if ($::opt_a || defined($::opt_n) || defined($::opt_N))
{
    if ($ENV{CT_MANAGEMENT_SCOPE}!=2 && $ENV{CT_MANAGEMENT_SCOPE}!=3)
    {
        $ENV{CT_MANAGEMENT_SCOPE}=4; 
    }
}

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

    if ( $node_file_name eq "-" )
    {
        $node_file_from_stdin = 1;
    } else
    {
        if ( check_input_file($node_file_name) )
        {
            exit(1);
        }
    }
}

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

# We have to parse the attr=val pairs so we can requote the values and replace the equals sign
foreach my $a (@ARGV)
  {
	# Note: we allow a null value
	my ($at, $val) = $a =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/;
	#if (!defined($at)) { $::MSGSET='createnode'; NodeUtils->message('E1','EMsgBAD_ATTR_VAL_FORM'); }
	if (!length($val)) { $val = "''"; }     # chrsrc-api needs something for the value
	# Put quotes around the value to protect spaces or weird chars
	# (if the value already has quotes around it, do not quote it)
	if (!( $val =~ /^(".*"|'.*')$/ ))
	  {
		# if the value has imbedded double quotes, use single quotes
		if ($val =~ /\"/) { $val = qq('$a'); }   # use the other quotes
		else 		# use double quotes
		  {
			$val =~ s/\"/\\\"/sg;     # escape embedded double quotes
			$val = qq("$val");
		  }
	  }
	$a = "${at}${DELIMITERI}$val";
  }
my $attrvals = join($DELIMITERI, @ARGV);

my $cmd = "";
if ($node_file_flag == 0)
{
    $cmd = qq(/usr/bin/chrsrc-api -I $DELIMITERI -D $DELIMITERO -s ${CLASSNAME}${DELIMITERI}${selectstr}${DELIMITERI}$attrvals$::opt_i 2>&1);
}
else
{
    if ($node_file_from_stdin != 0)
    {
        $node_file_name = read_from_Stdin();
    }

    $cmd = qq(/usr/bin/chrsrc-api -I $DELIMITERI -D $DELIMITERO -w ${CLASSNAME}${DELIMITERI}${selectstr}${DELIMITERI}${node_file_name}${DELIMITERI}$attrvals$::opt_i 2>&1);
}
if ($::opt_v) { $main::PROGNAME = 'lssensor'; printIMsg('IMsgRmcCmd', $cmd); $main::PROGNAME = 'chsensor'; }

my @output = `$cmd`;
my $rc= $?;
# remove temp node file if from STDIN
if ($node_file_from_stdin != 0)
{
    unlink($node_file_name);
}

if ($rc)
{
    if ($rc & 255)
    {
        printEMsg('EMsgChsensorSignalError', "chrsrc-api", $rc);   
    }
    else
    {
        $rc = $rc >> 8;
        if ($output[0] =~ /^ERROR.*/)
        {
            if (!$::opt_v) 
            { 
                $output[0] =~ s/^ERROR.*${DELIMITERO}//; 
            }
	    if ($rc == 6)
            {
                if ($::opt_v) { print $output[0]; }
                printEMsg('EMsgResNotDefinedCh',$name);
            }
            else
            {
                print $output[0];
            }

        }
        else
        {
            print @output;
            printEMsg('EMsgChsensorNonAPIError', "chrsrc-api", $rc);
        }
    }
}

exit $rc;