#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG
#  This is an automatically generated prolog.
#
#  Copyright (C) Altran ACT S.A.S. 2017,2018,2019,2021.  All rights reserved.
#
#  ALTRAN_PROLOG_END_TAG
#
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r714 src/43haes/lib/ksh93/hacmp/KLIB_HACMP_modify_event.sh 1.4 
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2012,2013 
# 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 
# @(#)  7d4c34b 43haes/lib/ksh93/hacmp/KLIB_HACMP_modify_event.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM

#================================================
# The following, commented line enforces coding
# standards when this file is edited via vim.
#================================================
# vim:tabstop=4:shiftwidth=4:expandtab:smarttab
#================================================

# Start of POD-formatted documentation. Viewing suggestions:
#      perldoc <FILENAME>
#      pod2text -c <FILENAME>
#      pod2text -c --code <FILENAME>
#      pod2html <FILENAME>
function devDoc {
    : <<'=cut' >/dev/null 2>&1

=head1 NAME

 KLIB_HACMP_modify_event

=head1 SYNOPSIS

 clmgr modify event <event> \
             [ NAME=<new_event_label> ] \
             [ FILE=<EXECUTABLE_FILE> ] \
             [ DESCRIPTION=<EVENT_DESCRIPTION> ]

 clmgr modify event <PRE-DEFINED_EVENT_NAME> \
             [ NOTIFY_COMMAND=<COMMAND_OR_FILE> ] \
             [ PRE_EVENT_COMMAND=<CUSTOM_EVENT_OR_FILE> ] \
             [ POST_EVENT_COMMAND=<CUSTOM_EVENT_OR_FILE> ] \
             [ PREPOSTFAILS={false|true} ]

 NOTE: the alias for "event" is "ev".

=head1 DESCRIPTION

Attempts to modify the specified cluster event
to conform to the provided specifications.

=head1 ARGUMENTS

 1. properties [REQUIRED] [hash ref]
    An associative array within which data about the
    modified object can be returned to the caller.

 2. event [REQUIRED] [string]
    The label of the event that is to be modified.

 3. new_name [OPTIONAL] [string]
    A new label to attempt to apply to the specified event.

 4. file [REQUIRED] [string]
    This is the command or script to be executed when the custom event
    happens. It is a required field for each custom event and cannot
    be changed for predefined events. 

 5. description [OPTIONAL] [string]
    A description of the event. If not description is
    specified, a default will be provided.

 6. notify_command [OPTIONAL] [abs_path]
    This is an optional command to run both before and after the
    event command is executed. The main purpose for this command
    is to notify the system administrator that a certain event
    has happened.

 7. pre_event_command [OPTIONAL] [custom_event_or_abs_path]
    This is an optional command to run before the event command is
    executed. This is used to provide pre-event processing by the
    PowerHA SystemMirror administrator. Multiple commands are
    allowed and must be delimited by a comma. You can also specify 
    custom events, and mix absolute path and custom event names.

 8. post_event_command [OPTIONAL] [custom_event_or_abs_path]
    This is an optional command to run after the event command is
    executed. This is used to provide post-event processing by the
    PowerHA SystemMirror administrator. Multiple commands are
    allowed and must be delimited by a comma. You can also specify 
    custom events, and mix absolute path and custom event names.

 9. prepostfails [OPTIONAL] {false|true}
    If set to true, failure of any user supplied pre or post event will 
    fail the event and skip any remaining processing for the event. 
    Default is false: failure of any user supplied pre or post event
    is ignored.

=head1 RETURN

 0: no errors were detected; the operation appears to have been successful
 1: a general error has occurred
 2: a specified resource does not exist, or could not be found
 3: some required input was missing
 4: some detected input was incorrect in some way
 5: a required dependency does not exist
 6: a specified search failed to match any data

=cut
} # End of POD-formatted documentation.


function KLIB_HACMP_modify_event {
    LINENO=2 . $HALIBROOT/log_entry "$0()" "$CL"
    : INPUTS: $*

    typeset -n properties=$1
    typeset event=${2//\"/}
    typeset new_name=${3//\"/}
    typeset file=${4//\"/}
    typeset desc=${5//\"/}
    typeset notify_command=${6//\"/}
    typeset pre_event_command=${7//\"/}
    typeset post_event_command=${8//\"/}
    typeset -l prepostfails=${9//\"/}

    [[ $CLMGR_LOGGING == 'med' ]] && set +x  # Only trace param values

    #================================================================
    : Check for a defined cluster. No need to continue without one.
    #================================================================
    CL=$LINENO isClusterDefined
    if (( $? != RC_SUCCESS )); then
        log_return_msg "$RC_MISSING_DEPENDENCY" "$0()" "$LINENO"
        return $?
    fi

    #===================================
    : Declare and initialize variables
    #===================================
    typeset -i rc=$RC_UNKNOWN
    typeset -i i=0
    typeset -i PREDEFINED_EVENT_MODS=0
    typeset key="" TYPE=""

    for key in COMMAND NOTIFY_COMMAND PRE_EVENT_COMMAND \
                   POST_EVENT_COMMAND PREPOSTFAILS
    do
        if [[ " ${!_ENV_ARGS[*]} " == *\ $key\ * ]]; then
            PREDEFINED_EVENT_MODS=1
            break
        fi
    done

    #================================================================
    : Assuming an object was specified, see if it is a known object
    #================================================================
    if [[ $event != *([[:space:]]) ]]; then
        CL=$LINENO KLIB_HACMP_is_known_event "$event" "" TYPE
        (( $? != RC_SUCCESS )) && rc=$RC_NOT_FOUND
    fi

    if [[ $TYPE == "CUSTOM" ]] && (( PREDEFINED_EVENT_MODS )); then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 9999 '\nERROR: one or more of the specified options is not compatible with "%1$s", which is a "%2$s" event.\n\n' "$event" "$TYPE" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    #=================
    : Validate input
    #=================
    if [[ -z $event ]]; then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 100 "\nERROR: a name/label must be provided.\n\n" 1>&2
        rc=$RC_MISSING_INPUT

    elif (( $rc == RC_NOT_FOUND )); then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 102 "\nERROR: \"%1\$s\" does not appear to exist!\n\n" "$event" 1>&2
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 170 "Available Events:\n\n" 1>&2

        typeset available
        CL=$LINENO KLIB_HACMP_list_events available
        for (( i=0; i<${#available[*]}; i++ )); do
            if [[ ${available[$i]} != *([[:space:]]) ]]; then
                print -u2 "\t${available[$i]}"
            fi
        done
        print -u2 ""
    fi

    if [[ -n $description && $description == *:* ]]; then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 103 "\nERROR: one or more invalid characters were detected in \"%1\$s\":  \"%2\$s\".\n\n" DESCRIPTION ":" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ -n $file ]]; then
       if [[ $file != /* ]]; then
            dspmsg -s $CLMGR_SET $CLMGR_MSGS 106 "\nERROR: the specified path does not appear to be in absolute format:\n%1\$s\n\n" "$file" 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ ! -e $file ]]; then
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 107 '\nERROR: the specified path/file does not appear to exist on "%2$s": %1$s\n\n' "$file" "$LOCAL_NODE" 1>&2
            rc=$RC_NOT_FOUND
        fi

        if [[ $file == *[[:space:]]* ]]; then
            dspmsg -s $CLMGR_SET $CLMGR_MSGS 108 "\nERROR: the \"%1\$s\" attribute's value contains whitespace,\nwhich is not allowed: \"%2\$s\"\n\n" FILE "$file" 1>&2
            rc=$RC_INCORRECT_INPUT
        fi
    fi

    if [[ -n $pre_event_command ]]; then
        typeset cmdEvt=""
        for cmdEvt in ${pre_event_command//,/ }; do
            CL=$LINENO KLIB_HACMP_is_known_event "$cmdEvt" CUSTOM
            if (( $? != RC_SUCCESS )); then
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 102 "\nERROR: \"%1\$s\" does not appear to exist!\n\n" "$cmdEvt" 1>&2
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 170 "Available Events:\n\n" 1>&2

                typeset available
                CL=$LINENO KLIB_HACMP_list_events available
                for (( i=0; i<${#available[*]}; i++ )); do
                    if [[ ${available[$i]} != *([[:space:]]) ]]; then
                        print -u2 "\t${available[$i]}"
                    fi
                done
                print -u2 ""

                rc=$RC_INCORRECT_INPUT
            fi
        done # End of the event loop
    fi

    if [[ -n $post_event_command ]]; then
        typeset cmdEvt=""
        for cmdEvt in ${post_event_command//,/ }; do
            CL=$LINENO KLIB_HACMP_is_known_event "$cmdEvt" CUSTOM
            if (( $? != RC_SUCCESS )); then
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 102 "\nERROR: \"%1\$s\" does not appear to exist!\n\n" "$cmdEvt" 1>&2
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 170 "Available Events:\n\n" 1>&2

                typeset available
                CL=$LINENO KLIB_HACMP_list_events available
                for (( i=0; i<${#available[*]}; i++ )); do
                    if [[ ${available[$i]} != *([[:space:]]) ]]; then
                        print -u2 "\t${available[$i]}"
                    fi
                done
                print -u2 ""

                rc=$RC_INCORRECT_INPUT
            fi
        done # End of the event loop
    fi

    if [[ "$new_name$desc$file$notify_command$pre_event_command$post_event_command$prepostfails" == *([[:space:]]) ]] && (( ! PREDEFINED_EVENT_MODS )); then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 401 "\nERROR: no valid modifications were specified for \"%1\$s\".\n\n" "$event" 1>&2
        rc=$RC_MISSING_INPUT
    fi

    #========================================================
    : Modify the event if no input errors have been detected
    #========================================================
    if (( $rc == RC_UNKNOWN )) && [[ "$new_name$desc$file" != *([[:space:]]) ]]
    then
        if [[ -z $desc || -z $file ]]; then
            : Preserve any pre-existing values
            typeset -A eProps
            CL=$LINENO KLIB_HACMP_get_event_attributes "$event" eProps
            [[ -z $desc ]] && desc=${eProps[DESCRIPTION]}
            [[ -z $file ]] && file=${eProps[FILE]}
        fi

        [[ -n $new_name ]] && new_name_opt=" -N $new_name"
        [[ -n $desc ]]     && desc_opt=" -I \"$desc\""
        [[ -n $file ]]     && file_opt=" -v $file"

        print "$0()[$LINENO]($SECONDS): clchcustom -t event -n\"$event\"$new_name_opt$file_opt$desc_opt" >>$CLMGR_TMPLOG  # Always log commands
        eval clchcustom -t event -n"$event"$new_name_opt$file_opt$desc_opt
        rc=$?
        print "$0()[$LINENO]($SECONDS): clchcustom RC: $rc" >>$CLMGR_TMPLOG  # Always log command result

        #=====================================================
        : If a custom event was successfully renamed, update
        : it in the predefined events, too, as needed.
        #=====================================================
        if [[ -n $new_name && $TYPE == "CUSTOM" ]] && (( $rc == RC_SUCCESS )); then
            typeset predef
            CL=$LINENO KLIB_HACMP_list_events predef TYPE=PREDEFINED
            for (( i=0; i<${#predef[*]}; i++ )); do
                typeset -A eProps
                CL=$LINENO KLIB_HACMP_get_event_attributes "${predef[$i]}" eProps TYPE=PREDEFINED
                for key in PRE_EVENT_COMMAND POST_EVENT_COMMAND; do
                    if [[ ${eProps[$key]} == $event ]]; then
                        dspmsg -s $CLMGR_SET $CLMGR_MSGS 9999 '*** Updating "%1$s" in event "%2$s" from "%3$s" to "%4$s".\n' "$key" "${eProps[NAME]}" "$event" "$new_name"
                        case $key in
                            PRE_EVENT_COMMAND)
                                clmgr -T $CLMGR_TRANSACTION_ID modify event "${predef[$i]}" PRE_EVENT_COMMAND=$new_name
                            ;;
                            POST_EVENT_COMMAND)
                                clmgr -T $CLMGR_TRANSACTION_ID modify event "${predef[$i]}" POST_EVENT_COMMAND=$new_name
                            ;;
                        esac
                        cmd_rc=$?
                        if (( $rc == RC_SUCCESS && $cmd_rc != RC_SUCCESS )); then
                            rc=$cmd_rc
                            dspmsg -s $CLMGR_SET $CLMGR_MSGS 9999 '\nERROR: failed to update "%1$s" in event "%2$s" from "%3$s" to "%4$s".\n\n' "$key" "${eProps[NAME]}" "$event" "$new_name" 1>&2
                        fi
                    fi
                done
                unset eProps
            done
        fi

        #===========================================================
        : If output from this operation was requested, retrieve it
        #===========================================================
        if (( $rc == RC_SUCCESS )); then
            if (( CLMGR_VERBOSE )) || [[ -n $CLMGR_ATTRS ]]; then
                CL=$LINENO KLIB_HACMP_get_event_attributes "$event" properties
            fi
        fi
    fi

    if (( $rc == RC_UNKNOWN || $rc == RC_SUCCESS )) &&
       (( PREDEFINED_EVENT_MODS ))
    then
        typeset sOpt= nOpt= bOpt= aOpt= pOpt=
        typeset -A eventAttrs
        CL=$LINENO KLIB_HACMP_get_event_attributes "$event" eventAttrs

        if [[ $notify_command != *([[:space:]]) ]]; then
            nOpt=" -n $notify_command"
        elif [[ " ${!_ENV_ARGS[*]} " != *\ NOTIFY_COMMAND\ * && \
                ${eventAttrs[NOTIFY_COMMAND]} != *([[:space:]]) ]]
        then
            nOpt=" -n ${eventAttrs[NOTIFY_COMMAND]}"
        fi

        if [[ $prepostfails != *([[:space:]]) ]]; then
            [[ $prepostfails == @(y|t)* ]] && pOpt=" -p 1" 
        elif [[ " ${!_ENV_ARGS[*]} " != *\ PREPOSTFAILS\ * && \
                ${eventAttrs[PREPOSTFAILS]} != *([[:space:]]) ]]
        then
            [[ ${eventAttrs[PREPOSTFAILS]} == @(y|t)* ]] && pOpt=" -p 1" 
        fi

        if [[ $pre_event_command != *([[:space:]]) ]]; then
            bOpt=" -b $pre_event_command"
        elif [[ " ${!_ENV_ARGS[*]} " != *\ PRE_EVENT_COMMAND\ * && \
                ${eventAttrs[PRE_EVENT_COMMAND]} != *([[:space:]]) ]]
        then
            bOpt=" -b ${eventAttrs[PRE_EVENT_COMMAND]}"
        fi

        if [[ $post_event_command != *([[:space:]]) ]]; then
            aOpt=" -a $post_event_command"
        elif [[ " ${!_ENV_ARGS[*]} " != *\ POST_EVENT_COMMAND\ * && \
                ${eventAttrs[POST_EVENT_COMMAND]} != *([[:space:]]) ]]
        then
            aOpt=" -a ${eventAttrs[POST_EVENT_COMMAND]}"
        fi

        print "$0()[$LINENO]($SECONDS): clchevent -O $event$sOpt$nOpt$bOpt$aOpt$pOpt" >>$CLMGR_TMPLOG
        clchevent -O $event$sOpt$nOpt$bOpt$aOpt$pOpt
        rc=$?
        print "$0()[$LINENO]($SECONDS): clchevent RC: $rc" >>$CLMGR_TMPLOG
    fi

    #=======================================================================
    : If a user input error was detected, provide some helpful suggestions
    #=======================================================================
    if (( $rc == RC_MISSING_INPUT || $rc == RC_INCORRECT_INPUT )) && \
       [[ $CLMGR_GUI == *([[:space:]]) ]]
    then
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 104 "For more information about available options and syntax, try\n\"$HAUTILS/clmgr %1\$s\". As an\nalternative, if the PowerHA SystemMirror man pages have been installed, invoke\n\"$HAUTILS/clmgr -hv\" (or \"/usr/bin/man clmgr\"),\nsearching for \"%2\$s\" in the displayed text.\n\n" \
        "modify event -h" "EVENT:" "$CLMGR_PROGNAME" 1>&2
    fi

    log_return_msg "$rc" "$0()" "$LINENO"
    return $?
} # End of "KLIB_HACMP_modify_event()"
