#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2001,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 = "@(#)19   1.18.1.18   src/rsct/rm/ER/cli/bin/chcondition.perl, errmcli, rsct_rady, rady2035a 11/12/15 16:39:52"
######################################################################
#                                                                    #
# Module: chcondition                                                #
#                                                                    #
# Purpose:                                                           #
#   chcondition - change attributes of a defined condition.          #
#                                                                    #
# Syntax:                                                            #
#   To change a condition:                                           #
#   chcondition [-h] [-r Resource_class]                             #
#               [-e Event_expression] [-E Rearm_expression]          #
#               [-d Event_Description] [-D Rearm_description]        #
#               [-b interval[,max_events][,retention_period]         #
#               [,max_total_size]                                    #
#               [-n Node_name[,Node_name,...]] [-S c|w|i] [-m l|d|p] #
#               [-s "Selection_string"]                              #
#               [-g 0|1|2][-TV] Condition[:Node_name]                #
#                                                                    #
#   To rename a condition:                                           #
#   chcondition [-h] -c New_condition [-TV] Condition[:Node_name]    #
#                                                                    #
#   To unlock or lock a condition:                                   #
#   chcondition [-h] -U|-L [-TV] Condition[:Node_name]               #
#                                                                    #
#                                                                    #
# Flags:                                                             #
#   -h      help - writes this command's usage statement to stdout   #
#   -b interval[,max_events]                                         #
#           The events are to be batched together for the interval   #
#           specified or until the max_events number of events are   #
#           generated. The interval restarts if the max_events number#
#           of events is reached before the interval expires. The    #
#           batching continues until there are no events generated   #
#           for an interval.  Use an interval of 0 to turn batching  #
#           off.  max_events cannot be specified unless interval is  #
#           greater than 0. When interval is greater than 0 and      #
#           max_events is 0, no maximum number of events is used. By #
#           default, max_events is 0 when interval is greater than 0.#
#           retention_period is to specify the retention period in   #
#           hour. Batched event file is saved for the time specified #
#           as retention period. Once this time is reached the file  #
#           is automatically deleted.                                #
#           max_totalsize is to specify the total size for the       #
#           batched event file in MB(MegaBytes). Batched event file  #
#           is saved until the size is reached, Once the size is     #
#           reached the file is automatically deleted.               #
#           If both retention_period and max_totalsize are specified,#
#           then Batched event file is saved, until whichever occur  #
#           first.                                                   #
#   -c      A new name to be assigned to this condition              #
#   -r      Resource_class.  The name of the resource class to be    #
#           monitored.                                               #
#   -e      Event_expression. Expression that determines when an     #
#           event occurs.  Expression usually involves the dynamic   #
#           attribute and a comparison.                              #
#   -E      Rearm_expression. Expression to indicate when to restart #
#           monitoring after an event has occurred.  Expression      #
#           usually involes the dynamic attribute and a comparison.  #
#   -d      Event_description. User supplied text to describe the    #
#           event_expression.                                        #
#   -D      Rearm_description. User supplied text to describe the    #
#           rearm_expression.                                        # 
#   -n      Nodelist where condition is to be defined.               #
#   -s      Selection_string. Specifies which resources in           #
#           the resource class are monitored.  Default is all        #
#           resources in the class.                                  #
#   -S c|w|i Specifies the severity of the event. c=critical,        #
#           w=warning, and i=informational.  Default is              #
#           informational.                                           #
#   -m l|d|p Specifies the scope of the condition when monitoring    #
#           starts. l=local, d=distribued domain, and p=peer domain. #
#   -g 0|1|2 Specifies granularity levels to control AuditLog records#
#           for the condition. Three levels of granularities are     #
#           provided 0:enable,1: only on error and 2:disable         #
#   -L      Lock. Lock the condition definition so no more changes   #
#           can be made.                                             #
#   -U      Unlock. Unlock the condition definition so changes to    #
#           the definition can be made.                              #
#   -T      Trace. IBM Support Center use only.                      #
#   -V      Verbose.                                                 #
#                                                                    #
# Operands:                                                          #
#   Condition       The name of an existing condition.  Node_name    #
#                   specifies where the condition is defined.        #
#                                                                    #
# Description:                                                       #
#   The chcondition command changes the attributes of a defined      #
#   condition to the value supplied on this command. If the name of  #
#   the condition is changed using the -c flag, any links with       #
#   responses remain intact.                                         #
#                                                                    #
# Exit Values:                                                       #
#   0  ERRM_CLI_SUCCESS      Command completed successfully.         #
#   1  ERRM_CLI_RMC_ERROR    Command terminated due to an underlying #
#                            RMC error.                              #
#   2  ERRM_CLI_ERROR        Command terminated due to an underlying #
#                            error in the command script.            #
#   3  ERRM_CLI_BAD_FLAG     Command terminated due to user          #
#                            specifying an invalid flag.             #
#   4  ERRM_CLI_BAD_OPERAND  Command terminated due to user          #
#                            specifying a bad operand.               #
#   5  ERRM_CLI_USER_ERROR   Command terminated due to a user error. #
#                            For example specifying a name that      #
#                            already exists.                         #
#                                                                    #
# Examples:                                                          #
#   1. To change the condition name from "JFS space used up" to      #
#      "Watch JFS space":                                            #
#      chcondition -c "Watch JFS space" "JFS space used up"          #
#   2. To change the rearm expression and rearm description for a    #
#      condition with the name "tmp space used up":                  #
#      chcondition -E "PercentTotUsed < 80"     \                    #
#           -D "Start monitoring tmp again after it is < 80% full" \ #
#           "tmp space used up"                                      #
#                                                                    #
# Man Page:                                                          #
#   For the most current detailed description of this command see    #
#   the chcondition man page in /opt/rsct/man.                  #
#                                                                    #
#--------------------------------------------------------------------#
# Inputs:                                                            #
#   /opt/rsct/msgmaps/errmcli.chcondition.map - message mapping #
#                                                                    #
# Outputs:                                                           #
#   stdout - display information on the condition.                   #
#   stderr - any error message.                                      #
#                                                                    #
# External Ref:                                                      #
#   Commands: ctdspmsg                                               #
#   Modules:  ERRM_cli_utils.pm, ERRM_cli_rc.pm                      #
#             CT_cli_utils.pm                                        #
#   Perl library routines: Getopt::Std                               #
#                                                                    #
# Tab Settings:                                                      #
#   4 and tabs should be expanded to spaces before saving this file. #
#   in vi:  (:set ts=4  and   :%!expand -4)                          #
#                                                                    #
# Change Activity:                                                   #
#   001222 JAC 67470: Initial design & write.                        #
#   010103 JAC 70296: Make TRUE/FALSE come from utils.               #
#   010116 JAC 70594: Modify selection string processing.            #
#   010122 JAC 70355: Update messages from final command doc.        #
#   010126 JAC 70783: Place NodeName value in single quotes.         #
#   010129 JAC 70951: Shift rc after RMC call if error occurs.       #
#   010303 JAC 71974: Switch parameters on bad severity message.     #
#   010308 JAC 71005: Escape some special characters in strings.     #
#   010507 JAC 73620: Check for RMC CLI user error (rc=5) and        #
#                     return ERRM user error for this case.          #
#   010516 JAC 74036: Convert nodenames to long names, if possible   #
#   011120 JAC 77597: Distributed RMC. Check for locator.            #
#   011206 JAC 78841: Fix selection string for locating resources.   #
#   011213 JAC 78976: Fix selection string for locating resources.   #
#   020121 JAC 79558: Fix selection string for locating resources.   #
#   020128 JAC 79559: Change how destination/locator node is used.   #
#   020419 JAC 81754: Use xxx-api where possible.                    #
#   020428 JAC 82364: Change mgt scope to l|d|p from l|c|s.          #
#   020719 JAC 84425: Add $rc to process_api_error call.             #
#   020722 JAC 84980: Allow -n to be blank ("") to reset nodes.      #
#   020725 JAC 84654: Change mgt scope to l|m|p from l|d|p.          #
#   020729 JAC 85061: Use 4 (DM/SR/local) for scope if locator used  #
#                     and scope not set.                             #
#   030620 JAC 96060: Add -U|-L for Locked attribute.                #
#   040407 JAC 105863: Use escape_chars for "\" searches.            #
#   070724 JAC 141919: Add error msg for -n with -m l.               #
#   071016 JAC 146726: Set delimiter for -api calls.                 #
#   071220 JAC 148224: Fix typo error.                               #
#   081106 JAC 153204: add batching flag.                            #
######################################################################

#--------------------------------------------------------------------#
# General Program Flow/Logic:                                        #
#                                                                    #
# 1. Parse command line flags and operands, determine which flavor   #
#    of this command we are actually invoking.                       #
#    This command allows a user to change conditions                 #
# 2. Print usage if -h specified                                     #
# 3. Make sure one and only one condition is specified               #
# 4. Make sure the condition exists.                                 #
# 5. If renaming a condition, make sure the new name doesn't exist.  #
# 6. If renaming a condition, rename by condition handle.            #
# 7. Translate flags into attribute names for RMC chrsrc command.    #
# 8. Call RMC command chrsrc. Also pass along -VT if necessary.      #
# 9. Return back any errors.                                         #
#                                                                    #
#--------------------------------------------------------------------#

#--------------------------------------------------------------------#
# Included Libraries and Extensions                                  #
#--------------------------------------------------------------------#
use lib "/opt/rsct/pm";
use locale;
use Getopt::Long;

use CT_cli_utils qw(printIMsg
                    printEMsg);
use CT_cli_input_utils qw(escape_chars);

use ERRM_cli_rc qw(ERRM_CLI_SUCCESS ERRM_CLI_RMC_ERROR
                   ERRM_CLI_ERROR ERRM_CLI_BAD_FLAG
                   ERRM_CLI_BAD_OPERAND ERRM_CLI_USER_ERROR);
use ERRM_cli_utils qw(error_exit
                    printCIMsg
                    printCEMsg
                    find_resource_name get_source_node
                    get_handle get_locator_node
                    set_orig_rmc_scope check_set_cluster_scope
                    process_api_error process_exit_code
                    change_locked_attr
                    $TRUE $FALSE
                    $CTDIR $CTBINDIR
                    $DELIMITERI $DELIMITERO
                    $SEVCRIT $SEVWARN $SEVINFO
                    $MKCNDCRIT $MKCNDWARN $MKCNDINFO
                    $LCL_SCOPE $SR_SCOPE $CSM_SCOPE
                    $SR_SCOPE_OLD $CSM_SCOPE_OLD $CSM_SCOPE_OLD2
                    $LCL_SCOPE_VAL $SR_SCOPE_VAL $CSM_SCOPE_VAL
                    $RMC_CLI_USER_ERROR $RMC_LOCAL_SCOPE
                    $MAX_UINT32
                    $CHRSRC $RSCCOND);


#--------------------------------------------------------------------#
# Global Variables                                                   #
#--------------------------------------------------------------------#
Getopt::Long::Configure ("bundling", "no_auto_abbrev", 
                         "no_ignore_case", "require_order",
                         "prefix_pattern=(--|-)");
$Trace = $FALSE;                        # default - trace off 
$Verbose = $FALSE;                      # default - verbose turned off

$Scope_orig_set = $FALSE;               # default - no CT_MANAGEMENT_SCOPE
$Scope_orig_value = 0;                  # default - scope value

$Opt_Resource = $FALSE;                 # default - no resource
$Opt_Event_Expr = $FALSE;               # default - no event expr
$Opt_Event_Descr = $FALSE;              # default - no event descr
$Opt_Rearm_Expr = $FALSE;               # default - no rearm expr
$Opt_Rearm_Descr = $FALSE;              # default - no rearm descr
$Opt_Selection = $FALSE;                # default - no selection
$Opt_Severity = $FALSE;                 # default - no severity
$Opt_Nodes = $FALSE;                    # default - no node list
$Opt_Rename_Condition = $FALSE;         # default - no rename condition
$Opt_Mgt_Scope = $FALSE;                # default - no management scope
$Opt_Lock = $FALSE;                     # default - no set lock
$Opt_Unlock = $FALSE;                   # default - no set unlock
$Opt_Toggle= $FALSE;                    # default - no toggle  
$Opt_No_Toggle= $FALSE;                 # default - no no toggle expr
$Opt_Batch = $FALSE;                    # default - no event bacthing
$Opt_Batch_Max = $FALSE;                # default - no event max
$Opt_Batch_Ret = $FALSE;                # default - no file retention period
$Opt_Batch_Size = $FALSE;               # default - no file size
$Opt_Audit_Log  = $FALSE;               # default - no audit log control

$PROGNAME = "chcondition";              # Program Name for messages
$LSMSG = "$CTBINDIR/ctdspmsg";          # list / display message rtn
$MSGCAT = "errmcli.cat";                # msg catalogue for this cmd
$ENV{'MSGMAPPATH'} = "$CTDIR/msgmaps";  # msg maps used by $LSMSG

#--------------------------------------------------------------------#
# Variables                                                          #
#--------------------------------------------------------------------#
my $condition = "";                     # Condition to make
my $resource_name = "";                 # resource for -r flag
my $event_expr = "";                    # expression for -e
my $event_desc = "";                    # description for -d
my $rearm_expr = "";                    # expression for -E
my $rearm_desc = "";                    # description for -D
my $select_str = "";                    # select string for -s 
my $severity = 0;                       # default for -r
my $nodelist = "";                      # default for -n
my $new_nodelist = "";                  # resolved nodelist 74036
my $rename_condition = "";              # name for Condition rename
my $mgt_scope = "";                     # management scope -m
my $locator = "";                       # where condition is
my $passopts = "";                      # options to pass to RMC
my $other_opts = "";                    # options to pass to RMC
my $one_node = "";                      # one from nodelist 74036
my $node_select = "";                   # used for NodeNameList
my @nodes = ();                         # list of nodes 74036
my $hname = "";                         # used by gethost 74036
my $haliases = "";                      # used by gethost 74036
my $haddrtype = "";                     # used by gethost 74036
my $hlength = 0;                        # used by gethost 74036
my @haddrs = ();                        # used by gethost 74036
my $comma = "";                         # used by gethost 74036
my $lock_val = 0;                       # Locked attr value 
my $batch_interval = 0;                 # event batching interval
my $batch_max_events = 0;               # max events for batching
my $batch_ret_period = 0;               # time for batch event file to be saved
my $batch_max_totalsize = 0;            # max size for the batch event file
my $audit_log = 0;                      # audit log control flag

#--------------------------------------------------------------------#
# Main Code                                                          #
#--------------------------------------------------------------------#
my $rc = 0;

# save original rmc management scope value, in case it's changed later
if (defined $ENV{CT_MANAGEMENT_SCOPE}) {
   $Scope_orig_set = $TRUE;
   $Scope_orig_value = $ENV{CT_MANAGEMENT_SCOPE};
}

# parse the command line, exit if there are errors 
($rc, $condition, $resource_name, $event_expr, 
 $event_desc, $rearm_expr, $rearm_desc, $select_str, 
 $severity, $nodelist, $rename_condition, 
 $mgt_scope, $batch_interval, $batch_max_events, $batch_ret_period, $batch_max_totalsize, $audit_log, $locator) = &parse_cmd_line;
($rc == 0) || error_exit($rc);

if ($Verbose) { printIMsg("IMsgchconditionStart",$condition);}

# pass the trace or verbose flags to chrsrc
if ($Trace) { $passopts = $passopts." -T"; }
if ($Verbose) { $passopts = $passopts." -V"; }

# if only changing Locked attribute, do it and leave
if ($Opt_Lock || $Opt_Unlock) {

   # set lock value
   if ($Opt_Lock) { $lock_val = 1;}
   if ($Opt_Unlock) { $lock_val = 0;}

   # call function to change Locked attribute
   $rc = change_locked_attr($lock_val,$locator,$RSCCOND,$condition);

   if ($Verbose) { printIMsg("IMsgchconditionEnd",$condition);}
   exit($rc);
}

# for anything that's a string, escape any inner double quotes (71005)
$resource_name = escape_chars($resource_name);
$event_expr = escape_chars($event_expr);
$event_desc = escape_chars($event_desc);
$rearm_expr = escape_chars($rearm_expr);
$rearm_desc = escape_chars($rearm_desc);
$select_str = escape_chars($select_str);
$nodelist = escape_chars($nodelist);

# add any optional parameters of chcondition to pass to chrsrc
# if parameter not specified, may need to get it for copy
if ($Opt_Resource) {                    # resource present
   $other_opts = $other_opts."${DELIMITERI}ResourceClass${DELIMITERI}\"$resource_name\""; }
   
if ($Opt_Event_Expr) {                  # event expression present
   $other_opts = $other_opts."${DELIMITERI}EventExpression${DELIMITERI}\"$event_expr\""; }
   
if ($Opt_Event_Descr) {                 # event description present
   $other_opts = $other_opts."${DELIMITERI}EventDescription${DELIMITERI}\"$event_desc\""; }
   
if ($Opt_Rearm_Expr) {                  # rearm expression present
   $other_opts = $other_opts."${DELIMITERI}RearmExpression${DELIMITERI}\"$rearm_expr\""; }
   
if ($Opt_Rearm_Descr) {                 # rearm description present
   $other_opts = $other_opts."${DELIMITERI}RearmDescription${DELIMITERI}\"$rearm_desc\""; }
   
if ($Opt_Selection) {                   # selection string present
   $other_opts = $other_opts."${DELIMITERI}SelectionString${DELIMITERI}\"$select_str\""; }
   
if ($Opt_Severity) {                    # severity present
   $other_opts = $other_opts."${DELIMITERI}Severity${DELIMITERI}\"$severity\""; }
   
if ($Opt_Nodes) {                       # node list present
   $other_opts = $other_opts."${DELIMITERI}NodeNames${DELIMITERI}\"{$nodelist}\""; }

if ($Opt_Mgt_Scope) {                   # management scope present
   $other_opts = $other_opts."${DELIMITERI}ManagementScope${DELIMITERI}$mgt_scope"; }
  
#If audit log ionformation is provided
if ($Opt_Audit_Log) {
   $other_opts = $other_opts."${DELIMITERI}AuditLogControl${DELIMITERI}$audit_log"; }

if ($Opt_Toggle)                        # toggle
{
   $other_opts = $other_opts."${DELIMITERI}NoToggleExprFlag${DELIMITERI}0";
}
elsif ($Opt_No_Toggle)                  # no toggle
{
   $other_opts = $other_opts."${DELIMITERI}NoToggleExprFlag${DELIMITERI}1";
}
 
if ($Opt_Batch) {                       # batching events - interval 
   $other_opts = $other_opts."${DELIMITERI}EventBatchingInterval${DELIMITERI}\"$batch_interval\""; }

if ($Opt_Batch_Max) {                   # batching events - max events
   $other_opts = $other_opts."${DELIMITERI}EventBatchingMaxEvents${DELIMITERI}\"$batch_max_events\""; }
if ($Opt_Batch_Ret) {                   # batching events - retention period
   $other_opts = $other_opts."${DELIMITERI}BatchedEventRetentionPeriod${DELIMITERI}\"$batch_ret_period\""; }

if ($Opt_Batch_Size) {                   # batching events - max totalsize
   $other_opts = $other_opts."${DELIMITERI}BatchedEventMaxTotalSize${DELIMITERI}\"$batch_max_totalsize\""; }

# set CT_MANAGEMENT_SCOPE to original setting, in case it was used
set_orig_rmc_scope;

# if the destination node was not specified, change the local definition.
# Make sure rmc scope is set to local scope.
if ($locator eq "") {
   $ENV{CT_MANAGEMENT_SCOPE} = $RMC_LOCAL_SCOPE;
}
# a locator was specified, use it for NodeNameList
else {
   $node_select = " && NodeNameList |< {\\\"$locator\\\"}";

   # use DM/SR/Local scope if scope not set
   check_set_cluster_scope;
}

# if renaming a condition (-c), use handle to update name
if ($Opt_Rename_Condition) {            # rename the condition

   if ($Trace) { print STDERR "$PROGNAME: calling chrsrc-api\n";}

   @cmd_out = `$CTBINDIR/chrsrc-api -I $DELIMITERI -D $DELIMITERO -s ${RSCCOND}${DELIMITERI}"Name==\\\"$condition\\\" $node_select"${DELIMITERI}Name${DELIMITERI}"$rename_condition"${other_opts} 2>&1`;
   $rc = $?;

   }

else {              # use chrsrc by condition name
   # call chrsrc 
   if ($Trace) { print STDERR "$PROGNAME: calling chrsrc-api\n";}
   @cmd_out = `$CTBINDIR/chrsrc-api -I $DELIMITERI -D $DELIMITERO -s ${RSCCOND}${DELIMITERI}"Name==\\\"$condition\\\" $node_select"${other_opts} 2>&1`;

   $rc = $?;
   }

$rc = &process_exit_code($rc);
if ($Trace) {
   print STDERR "chrsrc-api results:\n";
   print STDERR "@cmd_out";
   print STDERR "$PROGNAME: chrsrc-api returned $rc\n";
}

# show any errors if there was a bad rc except for not found
if ($rc != 0) {
   process_api_error($DELIMITERO,$rc,@cmd_out);
}

# return ERRM CLI user error if it's an RMC CLI user error    73620
if ($Trace) { print STDERR "$PROGNAME: $CHRSRC returned $rc\n";}
($rc == $RMC_CLI_USER_ERROR) && ( error_exit(ERRM_CLI_USER_ERROR) );

# if chrsrc command failed, print RMC error message and exit
if ($rc != 0) {
    printCEMsg("EMsgERRMcliUnExpectRMCrc",$rc);
    exit(ERRM_CLI_RMC_ERROR);
    }

if ($Verbose) { printIMsg("IMsgchconditionEnd",$condition);}
exit($rc);

#--------------------------------------------------------------------#
# End Main Code                                                      #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# parse_cmd_line - Parse the command line for options and operands.  #
#   Set appropriate global variables as outlined below, make sure we #
#   have a valid combination of arguments / options.                 #
#                                                                    #
# Return:                                                            #
#   $rc   0                  Command line parsed fine, no problem.   #
#         ERRM_CLI_BAD_FLAG  Command line contained a bad flag.      #
#   $resource                Name of resource to be removed.         #
#                                                                    #
# Global Variables Modified:                                         #
#   $Verbose           output   True (-V) turn Verbose mode on.      #
#   $Trace             output   True (-T) turn Trace mode on.        #
#   $Opt_Resource      output   True (-r) resource specified         #
#   $Opt_Event_Expr    output   True (-e) event expression specified #
#   $Opt_Event_Descr   output   True (-d) event description specified#
#   $Opt_Rearm_Expr    output   True (-E) rearm expression specified #
#   $Opt_Rearm_Descr   output   True (-D) rearm description specified#
#   $Opt_Selection     output   True (-s) selection string specified #
#   $Opt_Severity      output   True (-S) severity specified         #
#   $Opt_Nodes         output   True (-n) node names specified       #
#   $Opt_Rename_Condition output True (-c) rename specified          #
#   $Opt_Mgt_Scope     output   True (-m) mgt scope specified        #
#   $Opt_Lock          output   True (-U) lock specified             #
#   $Opt_Unlock        output   True (-U) unlock specified           #
#   $Opt_Batch         output   True (-b) event batching specified   #
#   $Opt_Batch_Max     output   True (-b) max batching events spec   #
#--------------------------------------------------------------------#
sub parse_cmd_line 
{
my(@original_argv) = @ARGV;             # user enetered flags/parms 
my $resource = "";                      # condition name
my $select_str = "";                    # selection string from -s 
my $resource_name = "";                 # resource class from -r
my $event_expr = "";                    # expression from -e
my $event_desc = "";                    # description from -d
my $rearm_expr = "";                    # expression from -E 
my $rearm_desc = "";                    # description from -D
my $sev_value = "";                     # severity from -S
my $node_list = "";                     # hosts from -n
my $severity = $MKCNDINFO;              # default severity
my $rename_condition = "";              # new name for condition
my $mgt_scope = "";                     # mgt scope from -m
my $mgt_scope_val = 0;                  # mgt scope translated
my $locator = "";                       # where the condition is
my $temp_name = "";                     # copy of condition name
my %opts = ();                          # for options parsing
my $lock_flag = "";                     # for invalid flag message
my $lock_flag2 = "";                    # for invalid flag message
my $batch_interval = 0;                 # event batching interval (sec)
my $batch_max_events = 0;               # max number of batched events
my $batch_ret_period = 0;               # time for batch event file to be saved
my $batch_max_totalsize = 0;            # max size for the batch event file
my $audit_log = 0;                      # audit log control flag

# Process the command line...
if (!GetOptions(\%opts,
                'h'   ,
                'c=s' ,
                'r=s' ,
                'e=s' ,
                'E=s' ,                                              
                'd=s' ,                                              
                'D=s' ,      
                'n=s' ,
                's=s' ,      
                'S=s' ,      
                'm=s' ,      
                'b=s' ,      
                'g=s' ,      
                'U'   ,
                'L'   ,       
                'V'   ,      
                'T'   ,    
                'qtoggle'  ,  
                'qnotoggle' ))
{
    # if errors
    &print_usage;                       # display proper usage
    return ERRM_CLI_BAD_FLAG;           # return bad rc - bad flag 
}

# process h flag
if (defined $opts{h}) {                 # -h, help request
    &print_usage;                       # print usage statement
    exit(0);                            # all done with good return
}

if (defined $opts{T}) {                 # -T turn trace on
    $Trace = $TRUE;
}

if (defined $opts{V}) {                 # -V turn verbose mode on
    $Verbose = $TRUE;
}

# Get the arguments...
# Operands:  resource (only one condition resource allowed)
if ($#ARGV == 0) {                      # index 0 is last one
    $resource = shift @ARGV;            # user specified resources
   
    # extract the locator, if it exists
    ($temp_name, $locator) = get_locator_node($resource);
    # put back condition name without locator
    if ($locator ne "") {
       $resource = $temp_name;
    }

    # make sure the condition already exists
    $rc = find_resource_name($resource,$RSCCOND,$locator);
    if ($rc != 0) {                     # condition name found
        if ($rc != $RMC_CLI_USER_ERROR) {
           printEMsg("EMsgchconditionConditionNotFound",$resource);
           }
        exit(ERRM_CLI_USER_ERROR);
    }
}

else {            
    # no resource or too many resources specified 
    printCEMsg("EMsgERRMcliInvalidNumberOfOperands");
    &print_usage;
    return ERRM_CLI_BAD_OPERAND;
}

# check for lock/unlock flags
if ((defined $opts{L}) || (defined $opts{U})) { # -U,-L for unlock,lock

   # set global flag
   if ( defined $opts{L} ) { 
      $Opt_Lock = $TRUE; 
      $lock_flag = "L";
   }
   if ( defined $opts{U} ) { 
      $Opt_Unlock = $TRUE; 
      $lock_flag = "U";
   }

   # these flags are not allowed together or with the other flags (creEdDnsmS)
   if ( $Opt_Lock && $Opt_Unlock ) {
      $lock_flag = "L";
      $lock_flag2 = "U";
   }
   elsif (defined $opts{c}) { $lock_flag2 = "c";}
   elsif (defined $opts{r}) { $lock_flag2 = "r";}
   elsif (defined $opts{e}) { $lock_flag2 = "e";}
   elsif (defined $opts{E}) { $lock_flag2 = "E";}
   elsif (defined $opts{d}) { $lock_flag2 = "d";}
   elsif (defined $opts{D}) { $lock_flag2 = "D";}
   elsif (defined $opts{n}) { $lock_flag2 = "n";}
   elsif (defined $opts{s}) { $lock_flag2 = "s";}
   elsif (defined $opts{m}) { $lock_flag2 = "m";}
   elsif (defined $opts{S}) { $lock_flag2 = "S";}
   elsif (defined $opts{qtoggle}) { $lock_flag2 = "qtoggle";}
   elsif (defined $opts{qnotoggle}) { $lock_flag2 = "qnotoggle";}  

   if ( $lock_flag2 ne "" ) {
      printCEMsg("EMsgERRMcliImproperUsageCombination",$lock_flag,$lock_flag2);
      &print_usage;
      return ERRM_CLI_BAD_FLAG;
      }
}


# check for copy condition flag
if (defined $opts{c}) {                 # -c for rename condition
    $rename_condition = $opts{c};
    $Opt_Rename_Condition = $TRUE;      # opt flag specified
    if ($rename_condition eq ""){       # no name for -c
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-c");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
    else {
       # make sure the rename condition name does not already exists
       $rc = find_resource_name($rename_condition,$RSCCOND,$locator);
       if ($rc == $RMC_CLI_USER_ERROR) {
           exit(ERRM_CLI_USER_ERROR);
           }
       if ($rc == 0) {                  # condition name exists   
          printEMsg("EMsgchconditionConditionExists",$rename_condition);
          exit(ERRM_CLI_USER_ERROR);
       }
    }
}

# check for resource class to be monitored
if (defined $opts{r}) {                 # -r for resource class
    $resource_name = $opts{r};
    $Opt_Resource = $TRUE;              # opt flag specified
    if ($resource_name eq ""){          # no resource name for -r
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-r");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for event expression 
if (defined $opts{e}) {                 # -e for event expression 
    $event_expr = $opts{e};
    $Opt_Event_Expr = $TRUE;            # opt flag specified
    if ($event_expr eq ""){             # no expression for -e     
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-e");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for rearm event expression (not required)
if (defined $opts{E}) {                 # -E for rearm expr       
    $rearm_expr = $opts{E};         
    $Opt_Rearm_Expr = $TRUE;            # opt flag specified
    if ($rearm_expr eq ""){             # no text for -E     
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-E");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for event description (not required)
if (defined $opts{d}) {                 # -d for event expr descr
    $event_desc = $opts{d};         
    $Opt_Event_Descr = $TRUE;           # opt flag specified
    if ($event_desc eq ""){             # no text for -d
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-d");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for rearm event description (not required)
if (defined $opts{D}) {                 # -D for rearm expr descr
    $rearm_desc = $opts{D};
    $Opt_Rearm_Descr = $TRUE;           # opt flag specified
    if ($rearm_desc eq ""){             # no text for -D
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-D");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for selection string (not required)
if (defined $opts{s}) {                 # -s for selection string
    $select_str = $opts{s};
    $Opt_Selection = $TRUE;             # opt flag specified
    if ($select_str eq ""){             # no string for -s
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-s");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for audit log flag (not required)
if (defined $opts{g}) {                 # -g audit log information
    $audit_log = $opts{g};
    $Opt_Audit_Log = $TRUE;             # opt flag specified
    if ($audit_log eq "" || $audit_log !~ /^[0-2]$/) {             # no string for -g
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-g");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
}

# check for event severity (not required)
$severity = $MKCNDINFO;                 # default severity
if (defined $opts{S}) {                 # -S for severity 
    $sev_value = $opts{S};
    $Opt_Severity = $TRUE;              # opt flag specified
    if ($severity eq ""){               # no severity for -S
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-S");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
    else {                              # check severity used
      if ($sev_value eq $SEVCRIT) { $severity = $MKCNDCRIT; }
      elsif ($sev_value eq $SEVWARN) { $severity = $MKCNDWARN;}
      elsif ($sev_value eq $SEVINFO) { $severity = $MKCNDINFO;}
      else {                            # wrong severity
         printEMsg("EMsgchconditionInvalidSeverity","-S",$sev_value);
         return ERRM_CLI_USER_ERROR;
      }
    }           
}

# check for host list (not required)
if (defined $opts{n}) {                 # -n for node list
    $node_list = $opts{n};
    $Opt_Nodes = $TRUE;                 # opt flag specified

    # to use -n, you must use -m with a non-local scope
    if ( defined $opts{m} && ($opts{m} eq $LCL_SCOPE) ) {
       printEMsg("EMsgchconditionNFlagNeedMFlag");
       return ERRM_CLI_BAD_FLAG;
    }
}

# check for management scope (not required)
if (defined $opts{m}) {                 # -m for mgt scope
    $mgt_scope = $opts{m};
    $Opt_Mgt_Scope = $TRUE;             # opt flag specified
    if ($mgt_scope eq ""){              # no text for -m
       printCEMsg("EMsgERRMcliMissingRequiredFlagOperand","-m");
       &print_usage;
       return ERRM_CLI_BAD_OPERAND;
    }
    else {                              # check scope used
      if ($mgt_scope eq $LCL_SCOPE) { $mgt_scope_val = $LCL_SCOPE_VAL; }
      elsif ($mgt_scope eq $SR_SCOPE) {$mgt_scope_val = $SR_SCOPE_VAL;}
      elsif ($mgt_scope eq $SR_SCOPE_OLD) {$mgt_scope_val = $SR_SCOPE_VAL;}
      elsif ($mgt_scope eq $CSM_SCOPE) {$mgt_scope_val = $CSM_SCOPE_VAL;}
      elsif ($mgt_scope eq $CSM_SCOPE_OLD) {$mgt_scope_val = $CSM_SCOPE_VAL;}
      elsif ($mgt_scope eq $CSM_SCOPE_OLD2) {$mgt_scope_val = $CSM_SCOPE_VAL;}
      else {                            # wrong scope
         printEMsg("EMsgchconditionInvalidScope",$mgt_scope,"-m");
         &print_usage;
         return ERRM_CLI_BAD_OPERAND;
      }
    }
}


if (defined $opts{qnotoggle}) 
{
    if ($Opt_Rename_Condition)
    {
        printCEMsg("EMsgERRMcliImproperUsageCombination","qnotoggle","-c");
        &print_usage;
        return ERRM_CLI_BAD_FLAG;
    }    
    $Opt_No_Toggle= $TRUE;
}

if (defined $opts{qtoggle})
{
    if ($Opt_No_Toggle)
    {
        printCEMsg("EMsgERRMcliImproperUsageCombination","--qtoggle","--qnotoggle");
        &print_usage;
        return ERRM_CLI_BAD_FLAG;
    }
    if ($Opt_Rename_Condition)
    {
        printCEMsg("EMsgERRMcliImproperUsageCombination","qtoggle","-c");
        &print_usage;
        return ERRM_CLI_BAD_FLAG;
    }
    $Opt_Toggle= $TRUE;
}

# check for event batching  -b interval[,max_events]
if (defined $opts{b}) {                 # -b for event batching

    # get the interval and optional max events
    ($batch_interval, $batch_max_events, $batch_ret_period, $batch_max_totalsize) = split (/,/, $opts{b});
    if ($batch_interval ne "" ){
       if ( ($batch_interval < 0) || ($batch_interval > $MAX_UINT32) || !($batch_interval =~ /^[0-9]+$/) ){
          printEMsg("EMsgchconditionInvalidBInterval",$batch_interval,"-b");
          return ERRM_CLI_BAD_OPERAND;
       }
       else {
          $Opt_Batch = $TRUE;           # good interval
       }
    }
#    else {
 #      printEMsg("EMsgchconditionInvalidBInterval",$batch_interval,"-b");
  #     return ERRM_CLI_BAD_OPERAND;
  #  }

    # check the optional max events
    if ($batch_max_events ne "" ){
       if (($batch_max_events < 0) || ($batch_max_events > $MAX_UINT32)) {
          printEMsg("EMsgchconditionInvalidBMaxEvents",$batch_max_events,"-b");
          return ERRM_CLI_BAD_OPERAND;
       }
       else {
          $Opt_Batch_Max = $TRUE;       # good interval
       }
    }
     # check option retention period
    if ($batch_ret_period ne "" ){
       if (($batch_ret_period < 0) || ($batch_ret_period > $MAX_UINT32)) { 
          printEMsg("EMsgchconditionInvalidBRetPeriod",$batch_ret_period,"-b");
          return ERRM_CLI_BAD_OPERAND;
       }
       else {
          $Opt_Batch_Ret = $TRUE;       # good interval
       }
    }

    # check option max total size
    if ($batch_max_totalsize ne "" ){
       if (($batch_max_totalsize < 0) || ($batch_max_totalsize > $MAX_UINT32)) {
          printEMsg("EMsgchconditionInvalidBMaxTotalSize",$batch_max_totalsize,"-b");
          return ERRM_CLI_BAD_OPERAND;
       }
       else {
          $Opt_Batch_Size = $TRUE;       # good interval
       }
    }
}


# return everything back to main
return(0, $resource, $resource_name, $event_expr,
       $event_desc, $rearm_expr, $rearm_desc, $select_str, 
       $severity, $node_list, $rename_condition, 
       $mgt_scope_val, $batch_interval, $batch_max_events,$batch_ret_period,$batch_max_totalsize,
       $audit_log,$locator);      # success
}   # end parse_cmd_line


#--------------------------------------------------------------------#
# print_usage : print the usage statement (syntax) to stdout.        #
#--------------------------------------------------------------------#
sub print_usage
{
&printIMsg("IMsgchconditionUsage6");
}   # end print_usage