#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2017,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2009,2010 
# 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_appserver.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_appserver

=head1 VERSION

 Version Number:  1.6
 Last Extracted:  1/31/14 04:41:11
 Last Changed:    9/27/13 17:56:03

 Path, Component, Release(, Level):
 src/43haes/lib/ksh93/hacmp/KLIB_HACMP_modify_appserver.sh, hacmp.assist, 61haes_r714

=head1 SYNOPSIS

 clmgr modify application <application_controller> \
             [ NAME=<new_application_controller_label> ] \
             [ STARTSCRIPT="/path/to/start/script" ] \
             [ STOPSCRIPT ="/path/to/stop/script" ] \
             [ MONITORS={<monitor>[,<monitor#2>,...]|None} ] \
             [ STARTUP_MODE={background|foreground} ] \
             [ CPU_USAGE_MONITOR={yes|no} ] \
             [ PROCESS_TO_MONITOR_CPU_USAGE= "/absolute/path/to/application/process" ] \
             [ CPU_USAGE_MONITOR_INTERVAL="1 .. 120" ]

 NOTE: the aliases for "application_controller" are "ac" and "app".

=head1 DESCRIPTION

Attempts to modify the specified application controller
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. appname [REQUIRED] [string]
    The label of the controller that is to be modified.

 3. new_name [OPTIONAL] [string]
    The new label to attempt to apply to the specified controller.

 4. startscript [OPTIONAL] [path]
    The full path to a new start script to be used for this
    controller's application (i.e. to launch it).

 5. stopscript [OPTIONAL] [path]
    The full path to a new stop script to be used for this
    controller's application (i.e. to shut it down).

 6. monitors [OPTIONAL] [string]
    A list of application monitors to use with this controller.
    Specify "None" to disable the monitoring for this application controller. 

 7. startup_mode [OPTIONAL] [boolean]
    Indicates if the application should be started in the background
    (default behavior), or in the foreground.

 8. cpu_usage_monitor [OPTIONAL] [set]
    This attribute controls the monitoring of cpu and memory usage of
    an application configured in a cluster. Default value is "no" and
    valid values are yes and no.

 9. process_to_monitor_cpu [OPTIONAL] [string]
    Absolute path to application process for which CPU usage shall
    be monitored.

 10. cpu_usage_monitor_interval [OPTIONAL] [integer]
    Indicates the interval at which CPU usage shall be monitored for an
    application process. Default value is 10 minutes and valid range is
    1 minute to 120 minutes.

=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

=head1 COPYRIGHT

COPYRIGHT International Business Machines Corp. 2005,2010
All Rights Reserved

=cut
} # End of POD-formatted documentation.


function KLIB_HACMP_modify_appserver {
    LINENO=2 . $HALIBROOT/log_entry "$0()" "$CL"
    : version=@(#)  7d4c34b 43haes/lib/ksh93/hacmp/KLIB_HACMP_modify_appserver.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM
    : INPUTS: $*

    typeset -n properties=$1
    typeset appname=${2//\"/}
    typeset new_name=${3//\"/}
    typeset startscript=${4//\"/}
    typeset stopscript=${5//\"/}
    typeset monitors=${6//\"/}
            monitors=${monitors//,/ }
    typeset startup_mode=${7//\"/}
    typeset cpu_usage_monitor=${8//\"/}
    typeset process_to_monitor_cpu=${9//\"/}
    typeset cpu_usage_monitor_interval=${10//\"/}

    [[ $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

    #================================================================
    : Assuming an object was specified, see if it is a known object
    #================================================================
    if [[ $appname != *([[:space:]]) ]]; then
        CL=$LINENO KLIB_HACMP_is_known_appserver "$appname"
        (( $? != RC_SUCCESS )) && rc=$RC_NOT_FOUND
    fi
    
    typeset existing
    CL=$LINENO KLIB_HACMP_list_appservers existing 2>>$CLMGR_TMPLOG

    #=================
    : Validate input
    #=================
    if [[ -z $appname ]]; 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" "$appname" 1>&2
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 140 "Available Application Controllers:\n\n" 1>&2

        typeset available
        CL=$LINENO KLIB_HACMP_list_appservers available
        for (( i=0; i<${#available[*]}; i++ )); do
            if [[ ${available[$i]} != *([[:space:]]) ]]; then
                print -u2 "\t${available[$i]}"
            fi
        done
        print -u2 ""
    
    elif [[ " ${existing[*]} " == *\ $new_name\ * ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 229 "\nERROR: the specified object already exists: \"%1\$s\"\n\n" "$new_name" 1>&2
        rc=$RC_INCORRECT_INPUT

    elif [[ -n $new_name && -n "${new_name//[a-zA-Z0-9_]/}" ]]; then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 105 "\nERROR: one or more invalid characters were detected in \"%1\$s\" (\"%2\$s\").\n\nValid characters include letters, numbers, and underscores only.\n\n" "$new_name" "${new_name//[a-zA-Z0-9_]/}" 1>&2
        rc=$RC_INCORRECT_INPUT

    elif [[ -n $new_name && $newname == *[[:space:]]* ]]; then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 108 "\nERROR: the \"%1\$s\" attribute's value contains whitespace, which is not allowed: \"%2\$s\"\n\n" NAME "$new_name" 1>&2
        rc=$RC_INCORRECT_INPUT

    elif (( ${#new_name} > $MAX_NAME_LENGTH )); then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 1463 '\nERROR: Application Controller name %1$s should not be more than %2$d characters.\n' "$new_name" "$MAX_NAME_LENGTH" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ -n $startscript && $startscript != /* ]]; then
        MSG=$(dspmsg -s $CLMGR_SET $CLMGR_MSGS 106 "\nERROR: the specified path does not appear to be in absolute format:\n%1\$s\n\n" "$startscript")
        MSG="$MSG (STARTSCRIPT @ $LOCAL_NODE)"
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ -n $startscript && ! -e ${startscript%%+([[:space:]])*} ]]; then
        MSG=$(dspmsg -s $CLMGR_SET $CLMGR_MSGS 107 '\nERROR: the specified path/file does not appear to exist on "%2$s": %1$s\n\n' "$startscript" "$LOCAL_NODE")
        MSG="$MSG (STARTSCRIPT)"
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
        rc=$RC_NOT_FOUND
    fi

    if [[ -n $stopscript && $stopscript != /* ]]; then
        MSG=$(dspmsg -s $CLMGR_SET $CLMGR_MSGS 106 "\nERROR: the specified path does not appear to be in absolute format:\n%1\$s\n\n" "$stopscript")
        MSG="$MSG (STOPSCRIPT @ $LOCAL_NODE)"
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ -n $stopscript && ! -e ${stopscript%%+([[:space:]])*} ]]; then
        MSG=$(dspmsg -s $CLMGR_SET $CLMGR_MSGS 107 '\nERROR: the specified path/file does not appear to exist on "%2$s": %1$s\n\n' "$stopscript" "$LOCAL_NODE")
        MSG="$MSG (STOPSCRIPT)"
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ -n $startup_mode ]]; then
        case $startup_mode in
            @(B|b)*) startup_mode=background ;;
            @(F|f)*) startup_mode=foreground ;;
            *) dspmsg -s $CLMGR_SET $CLMGR_MSGS 110 "\nERROR: invalid value specified for \"%1\$s\":  \"%2\$s\".\n" STARTUP_MODE "$startup_mode" 1>&2
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 "Valid values: %1\$s\n\n" "background, foreground" 1>&2
                rc=$RC_INCORRECT_INPUT
            ;;
        esac
    fi

    # Valid values of cpu_usage_monitor are yes, no. Default value is 'no'.
    if [[ -n $cpu_usage_monitor ]]; then
       case $cpu_usage_monitor in
            @(Y|y|T|t|1)*) cpu_usage_monitor=yes ;;
            @(N|n|F|f|0)*) cpu_usage_monitor=no ;;
            *) dspmsg -s $CLMGR_SET $CLMGR_MSGS 110 "\nERROR: invalid value specified for \"%1\$s\":  \"%2\$s\".\n" CPU_USAGE_MONITOR "$cpu_usage_monitor" 1>&2
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 "Valid values: %1\$s\n\n" "no, yes" 1>&2
                rc=$RC_INCORRECT_INPUT
            ;;
        esac
    fi

    # process_to_monitor_cpu is a absolute path of an application process to be monitored
    if [[ -n $process_to_monitor_cpu ]]; then
        if [[ $process_to_monitor_cpu != /* ]]; then
            MSG=$(dspmsg -s $CLMGR_SET $CLMGR_MSGS 106 "\nERROR: the specified path does not appear to be in absolute format:\n%1\$s\n\n" "$process_to_monitor_cpu")
            MSG="$MSG (PROCESS_TO_MONITOR_CPU_USAGE @ $LOCAL_NODE)"
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ ! -e ${process_to_monitor_cpu%%+([[:space:]])*} ]]; then
            MSG=$(dspmsg -s $CLMGR_SET $CLMGR_MSGS 107 '\nERROR: the specified path/file does not appear to exist on "%2$s": %1$s\n\n' "$process_to_monitor_cpu" "$LOCAL_NODE")
            MSG="$MSG (PROCESS_TO_MONITOR_CPU_USAGE)"
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
            rc=$RC_NOT_FOUND
        fi
    fi

    # Valid values of cpu_usage_monitor_interval is 1 minute to 120 minutes.
    if [[ -n $cpu_usage_monitor_interval ]]; then
        if [[ $cpu_usage_monitor_interval != *([[:space:]]) ]]; then
            if [[ $cpu_usage_monitor_interval != +([0-9]) ]]; then
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 1312 'CPU usage monitor interval "%1$s" is not an integer. Provide an integer value in range of 1 minute to 120 minutes.\n' $cpu_usage_monitor_interval 1>&2
                rc=$RC_INCORRECT_INPUT
            else
                CL=$LINENO verify_numeric_range "$cpu_usage_monitor_interval" 1 120 CPU_USAGE_MONITOR_INTERVAL
                (( $? != RC_SUCCESS )) && rc=$RC_INCORRECT_INPUT
            fi
        fi
    elif [[ " ${!_ENV_ARGS[*]} " == *\ CPU_USAGE_MONITOR_INTERVAL\ * ]]; then
        dspmsg -s $CLMGR_SET $CLMGR_MSGS 1313 'CPU usage monitor interval is empty. Provide an integer value in range of 1 minute to 120 minutes.\n' 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    #======================================================================
    : Modify the application server if no input errors have been detected
    #======================================================================
    if (( $rc == RC_UNKNOWN )); then
        typeset CMD="$HAUTILS/clchserv -o$appname"

        [[ -z $new_name     ]] && new_name=$appname  # cllsserv always requires new name and old name,hence same name is passed when it is empty
        [[ -n $new_name     ]] && CMD="$CMD -s$new_name"
        [[ -n $startscript  ]] && CMD="$CMD -b'$startscript'"
        [[ -n $stopscript   ]] && CMD="$CMD -e'$stopscript'"
        [[ -n $startup_mode ]] && CMD="$CMD -O $startup_mode"
        [[ -n $cpu_usage_monitor_interval ]] && CMD="$CMD -i $cpu_usage_monitor_interval"
        [[ -n $cpu_usage_monitor ]] && CMD="$CMD -E $cpu_usage_monitor"

        #===========================================================
        : Allow user to reset PROCESS_TO_MONITOR_CPU_USAGE to empty string
        #===========================================================
        if [[ -n $process_to_monitor_cpu ]]; then
            CMD="$CMD -C $process_to_monitor_cpu"
        elif [[ " ${!_ENV_ARGS[*]} " == *\ PROCESS_TO_MONITOR_CPU_USAGE\ * ]]; then
            CMD="$CMD -C ''"
        fi

        if [[ -n $monitors || " ${!_ENV_ARGS[*]} " == *\ MONITORS\ * ]]; then
            print "$0()[$LINENO]($SECONDS): $CMD -m \"$monitors\"" >>$CLMGR_TMPLOG  # Always log commands
            # If monitor list input as case-sensitive "NONE",then consider it as "None"
            # None : Disable the monitoring for application controller
            typeset -l mon_list=$monitors
            if [ "$mon_list" == "none" ];then
                monitors='None'
            fi
            eval $CMD -M \"$monitors\"
        else
            print "$0()[$LINENO]($SECONDS): $CMD" >>$CLMGR_TMPLOG
            eval $CMD
        fi
        rc=$?
        print "$(basename ${CMD%% *}) RC: $rc" >>$CLMGR_TMPLOG

        if (( $rc != RC_SUCCESS )); then
            dspmsg -s $CLMGR_SET $CLMGR_MSGS 400 "\nERROR: failed to modify \"%1\$s\".\n\n" "$appname" 1>&2
            rc=$RC_ERROR
        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_appserver_attributes "$appname" properties
            fi
        fi
    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 application_controller -h" "APPLICATION CONTROLLER:" "$CLMGR_PROGNAME" 1>&2
    fi

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