#!/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. 2000,2007 
# 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 
# @(#)29   1.21   src/rsct/rm/SensorRM/cli/bin/mksensor.perl, sensorcli, rsct_relgh, relghs001a 8/7/06 15:38:07

# Creates an RMC sensor

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::Std;
use CT_cli_utils qw(printIMsg printEMsg);
use Socket;

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

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

# Parse the cmd line args and check them
if (! getopts('c:u:i:n:e:hvV') ) { &usage; }
if ($::opt_h) { &usage(0); }
if (scalar(@ARGV) < 2) { &usage; }

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

my $name = shift @ARGV;
my $cmd = join(' ', @ARGV);
my $username;

if (defined($::opt_c))
{
    $::opt_c= "::ControlFlags::$::opt_c";
}

if (defined($::opt_u))
{
    $username = $::opt_u;
}
else
{
    # we use whoami instead of $USER or $LOGNAME so it will work with su
    $username = `whoami`;
    chop $username;
}

if (!defined($::opt_i)) 
{ 
    $::opt_i= 60;
}
elsif ($::opt_i < 10 && $::opt_i != 0)
{
    printEMsg('EMsgMksensorInvInterval', $::opt_i);
    exit(1);
}

if (defined($::opt_n))
{
    if ($ENV{CT_MANAGEMENT_SCOPE}!=2 && $ENV{CT_MANAGEMENT_SCOPE}!=3)
    {
        $ENV{CT_MANAGEMENT_SCOPE}=4;
    }
    # Only 1 node is allowed with mksensor
    $::opt_n = "::NodeNameList::{'$::opt_n'}";
}

if (defined($::opt_e))
   {
    $::opt_e = "::ErrorExitValue::$::opt_e";
   }

# escape double quotes
$cmd =~ s/"/\\"/sg;
# escape $ characters
$cmd =~ s/\$/\\\$/sg;

my $cmd = qq(/usr/bin/mkrsrc-api IBM.Sensor::Name::"${name}"::Command::"${cmd}"::UserName::"${username}"::RefreshInterval::$::opt_i$::opt_c$::opt_n$::opt_e 2>&1);
if ($::opt_v) { $main::PROGNAME = 'lssensor'; printIMsg('IMsgRmcCmd', $cmd); $main::PROGNAME = 'mksensor'; }

my @output = `$cmd`;
my $rc= $?;

if ($rc)
{
    if ($rc & 255)
    {
        printEMsg('EMsgMksensorSignalError', "mkrsrc-api", $rc);   
    }
    else
    {
        $rc = $rc >> 8;
        if ($output[0] =~ /^ERROR.*/)
        {
            if (!$::opt_v) 
            { 
                $output[0] =~ s/^ERROR.*:://; 
            }
        }
        else
        {
            printEMsg('EMsgMksensorNonAPIError', "mkrsrc-api", $rc);
        }
        print @output;
    }
}

exit $rc;
