#!/usr/sbin/rsct/perl5/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2003,2008 
# 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 
#"@(#)27   1.13   src/rsct/rm/SensorRM/cli/bin/refsensor.perl, sensorcli, rsct_rfos, rfos0838a 5/6/08 08:35:37"

# Refreshes the a sensor resource in 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'} || '/usr/sbin/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
);
use Socket;

$main::PROGNAME = 'refsensor';
$main::MSGCAT = 'sensorcli.cat';
$main::LSMSG = '/usr/sbin/rsct/bin/ctdspmsg';

# For the usage, see sensorcli.msg
#sub usage { printIMsg('IMsgRefsensorUsage');  exit (scalar(@_) ? $_[0] : 1); }
#sub usage { printIMsg('IMsgRefsensorUsage2');  exit (scalar(@_) ? $_[0] : 1); }
sub usage { printIMsg('IMsgRefsensorUsage3');  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' ,
                'a' ,
                'm' ,
                'v' ,
                'V',
                'n=s',
                'N=s' ))
{
    &usage;
}
if ($::opt_h) { &usage(0); }
if (scalar(@ARGV) < 1 ||
    ( (scalar(@ARGV) != 1) && $::opt_m ) ||
    (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; }

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);
    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"); }

# fill in FieldIndicator from the args passed
my $fld_ind=0;
foreach my $b (@ARGV)
  {
     # Note: we allow a null value
     my ($at, $val) = $b =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/;

     if    ($b =~ /^String=/)  { 
           $fld_ind = $fld_ind | 1; 

        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 quote
             else   # use double quotes
               {
                 $val =~ s/\"/\\\"/sg;     # escape embedded double quotes
                 $val = qq("$val");
                }
          }
     }

     elsif ($b =~ /^Int32=/)   { $fld_ind = $fld_ind | 2; }
     elsif ($b =~ /^Uint32=/)  { $fld_ind = $fld_ind | 4; }
     elsif ($b =~ /^Int64=/)   { $fld_ind = $fld_ind | 8; }
     elsif ($b =~ /^Uint64=/)  { $fld_ind = $fld_ind | 16; }
     elsif ($b =~ /^Float32=/) { $fld_ind = $fld_ind | 32; }
     elsif ($b =~ /^Float64=/) { $fld_ind = $fld_ind | 64; }
     elsif ($b =~ /^Quantum=/) { $fld_ind = $fld_ind | 128; }
     else { 
           printEMsg('EMsgRefsensorInvAttr',$b);
           exit(1);
          }

     $b = "${at}${DELIMITERI}${val}";


  }

my $attrvals = join($DELIMITERI, @ARGV);

my $cmd = "";

if ($node_file_from_stdin != 0)
{
    $node_file_name = read_from_Stdin();
}
# decide which runact to do ... no args to RunCommand, else SetValues.
# -m not specified, use sensor actions
if (!$::opt_m)
{
if (scalar(@ARGV) < 1 )
{
      # no args so use RunCommand action
   if ( $node_file_flag == 0 )
   {
       $cmd = qq(/usr/bin/runact-api -I $DELIMITERI -D $DELIMITERO -s IBM.Sensor${DELIMITERI}${selectstr}${DELIMITERI}RunCommand${DELIMITERI}WaitCommandEnd${DELIMITERI}1 2>&1);
   }
   else
   {
       $cmd = qq(/usr/bin/runact-api -I $DELIMITERI -D $DELIMITERO -w IBM.Sensor${DELIMITERI}${selectstr}${DELIMITERI}${node_file_name}${DELIMITERI}RunCommand${DELIMITERI}WaitCommandEnd${DELIMITERI}1 2>&1);
   }
}
else
{
      # args so use SetValues
    if ( $node_file_flag == 0 )
    {
         $cmd = qq(/usr/bin/runact-api -I $DELIMITERI -D $DELIMITERO -s IBM.Sensor${DELIMITERI}${selectstr}${DELIMITERI}SetValues${DELIMITERI}FieldIndicator${DELIMITERI}${fld_ind}${DELIMITERI}${attrvals} 2>&1);
    }
    else
    {
         $cmd = qq(/usr/bin/runact-api -I $DELIMITERI -D $DELIMITERO -w IBM.Sensor${DELIMITERI}${selectstr}${DELIMITERI}${node_file_name}${DELIMITERI}SetValues${DELIMITERI}FieldIndicator${DELIMITERI}${fld_ind}${DELIMITERI}${attrvals} 2>&1);
    }
}
}

# -m specified for microsensors
else 
{
    if ( $node_file_flag == 0 )
    {
         $cmd = qq(/usr/bin/runact-api -I $DELIMITERI -D $DELIMITERO -s IBM.MicroSensor${DELIMITERI}${selectstr}${DELIMITERI}Refresh 2>&1);
    }
    else
    {
         $cmd = qq(/usr/bin/runact-api -I $DELIMITERI -D $DELIMITERO -w IBM.MicroSensor${DELIMITERI}${selectstr}${DELIMITERI}${node_file_name}${DELIMITERI}Refresh 2>&1);
    }
}


if ($::opt_v) { $main::PROGNAME = 'lssensor'; printIMsg('IMsgRmcCmd', $cmd); $main::PROGNAME = 'refsensor'; }

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

# if rc not 0, then some messages may be mixed in with action output
my @no_error_output =();
if ($rc)
  {
     foreach my $line (@output)
        {
             # is it an error message? if so print, if not, save
             if ($line =~ /^ERROR/) 
                { 
                   if (!$::opt_v) { $line =~ s/.*${DELIMITERO}.*${DELIMITERO}.*${DELIMITERO}.*${DELIMITERO}.*${DELIMITERO}//; }
                   print $line;
                } 
             else
                {
                   push (@no_error_output,$line);
                } 
        }
  }

else {@no_error_output = @output;}

# process action output 
# from RunCommand: Result=  0=success, 1=sensor not monitored, 2=error
# from SetValues:  Result=  Same as FieldIndicator  (Note: if Result=0, nothing updated)
#                           256=sensor not monitored

# get action Result value
(my $handle, my $result) = split /${DELIMITERO}Result${DELIMITERO}/, $no_error_output[0];

# for sensors
if (!$::opt_m)
{
   # if SetValue  
   if ($fld_ind) 
      {
         if ($result != $fld_ind)
            {
 
              $rc = 4;
              if ( ($fld_ind & 1) && !($result & 1) ) {
                    printEMsg('EMsgRefsensorNoEvent',"String");
                 }
              if ( ($fld_ind & 2) && !($result & 2) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Int32");
                 }
              if ( ($fld_ind & 4) && !($result & 4) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Uint32");
                 }
              if ( ($fld_ind & 8) && !($result & 8) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Int64");
                 }
              if ( ($fld_ind & 16) && !($result & 16) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Uint64");
                 }
              if ( ($fld_ind & 32) && !($result & 32) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Float32");
                 }
              if ( ($fld_ind & 64) && !($result & 64) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Float64");
                 }
              if ( ($fld_ind & 128) && !($result & 128) ) {
                    printEMsg('EMsgRefsensorNoEvent',"Quantum");
                 }
                 
            }
      }

   # else RunCommand
   else
      {
         if ($result == 1)  
            {
               printEMsg('EMsgRefsensorNotMon');
               $rc = 4;
            }
      }
}


exit $rc;

