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

=head1 VERSION

 Version Number:  1.11
 Last Extracted:  1/31/14 04:40:48
 Last Changed:    8/6/13 16:54:47

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

=head1 SYNOPSIS

 clmgr add application_controller <application_controller> \
             STARTSCRIPT="/path/to/start/script" \
             STOPSCRIPT ="/path/to/stop/script" \
             [ MONITORS=<monitor>[,<monitor#2>,...] ] \
             [ 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: aliases for "application_controller" are "ac" and "app".

=head1 DESCRIPTION

Attempts to create an application controller that conforms
to the provided specifications.

=head1 ARGUMENTS

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

 2. appname [REQUIRED] [string]
    The label to apply to the new controller object.

 3. start_script [REQUIRED] [string]
    The absolute/full path to the executable file that will be used
    to start the application associated with this controller object.

 4. stop_script [REQUIRED] [string]
    The absolute/full path to the executable file that will be used
    to stop the application associated with this controller object.

 5. monitors [OPTIONAL] [string]
    A list of application monitors that are to be used to monitor
    the application associated with this controller object.

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

 7. 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.
 
 8. process_to_monitor_cpu [OPTIONAL] [string]
    Absolute path to application process for which CPU usage shall
    be monitored.

 9. 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_add_appserver {
    LINENO=2 . $HALIBROOT/log_entry "$0()" "$CL"
    : version=@(#)  7d4c34b 43haes/lib/ksh93/hacmp/KLIB_HACMP_add_appserver.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM
    : INPUTS: $*

    typeset -n properties=$1
    typeset appname=${2//\"/}
    typeset start_script=${3//\"/}
    typeset stop_script=${4//\"/}
    typeset monitors=${5//\"/}
    typeset startup_mode=${6//\"/}
    typeset cpu_usage_monitor=${7//\"/}
    typeset process_to_monitor_cpu=${8//\"/}
    typeset cpu_usage_monitor_interval=${9//\"/}

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

    #===================================
    : Declare and initialize variables
    #===================================
    typeset -i rc=$RC_UNKNOWN

    typeset existing
    CL=$LINENO KLIB_HACMP_list_appservers existing 2>>$CLMGR_TMPLOG

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

    #=======================================================================
    : Validate input.
    : Must have a name, start and stop script - claddserv will do the rest
    : of the checking for valid names, etc
    #=======================================================================
    elif [[ -z $appname ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 100 "\nERROR: a name/label must be provided.\n\n" 1>&2
        rc=$RC_MISSING_INPUT

    elif [[ " ${existing[*]} " == *\ $appname\ * ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 229 "\nERROR: the specified object already exists: \"%1\$s\"\n\n" "$appname" 1>&2
        rc=$RC_INCORRECT_INPUT

    elif [[ -n $appname && -n "${appname//[a-zA-Z0-9_]/}" ]]; then
        /usr/bin/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" "$appname" "${appname//[a-zA-Z0-9_]/}" 1>&2
        rc=$RC_INCORRECT_INPUT

    elif (( ${#appname} > $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' "$appname" "$MAX_NAME_LENGTH" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ -z $start_script ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 101 "\nERROR: this operation requires the \"%1\$s\" attribute.\n\n" STARTSCRIPT 1>&2
        rc=$RC_MISSING_INPUT
    fi

    if [[ -z $stop_script ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 101 "\nERROR: this operation requires the \"%1\$s\" attribute.\n\n" STOPSCRIPT 1>&2
        rc=$RC_MISSING_INPUT
    fi

    if [[ -n $start_script && $start_script != /* ]]; then
        MSG=$(/usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 106 "\nERROR: the specified path does not appear to be in absolute format:\n%1\$s\n\n" "$start_script")
        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 $start_script && ! -e ${start_script%%+([[:space:]])*} ]]; then
        MSG=$(/usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 107 '\nERROR: the specified path/file does not appear to exist on "%2$s": %1$s\n\n' "$start_script" "$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 $stop_script && $stop_script != /* ]]; then
        MSG=$(/usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 106 "\nERROR: the specified path does not appear to be in absolute format:\n%1\$s\n\n" "$stop_script")
        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 $stop_script && ! -e ${stop_script%%+([[:space:]])*} ]]; then
        MSG=$(/usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 107 '\nERROR: the specified path/file does not appear to exist on "%2$s": %1$s\n\n' "$stop_script" "$LOCAL_NODE")
        MSG="$MSG (STOPSCRIPT)"
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS -1 "${MSG//+([[:space:]])/ }" 1>&2
        rc=$RC_NOT_FOUND
    fi

    if [[ -n $startup_mode ]]; then
        case $startup_mode in
            @(B|b)*) startup_mode=background ;;
            @(F|f)*) startup_mode=foreground ;;
            *) /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 110 "\nERROR: invalid value specified for \"%1\$s\":  \"%2\$s\".\n" STARTUP_MODE "$startup_mode" 1>&2
                /usr/bin/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" ;;
            *) /usr/bin/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
                /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 "Valid values: %1\$s\n\n" "no, yes" 1>&2
                rc=$RC_INCORRECT_INPUT
            ;;
        esac
    else
        cpu_usage_monitor="no"
    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=$(/usr/bin/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=$(/usr/bin/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
    else
        process_to_monitor_cpu=""
    fi

    # Valid values of cpu_usage_monitor_interval is 1 minute to 120 minutes.
    # Default value is 10 minutes.
    if [[ -n $cpu_usage_monitor_interval ]]; then
        if [[ $cpu_usage_monitor_interval != *([[:space:]]) ]]; then
            CL=$LINENO verify_numeric_range "$cpu_usage_monitor_interval" 1 120 CPU_USAGE_MONITOR_INTERVAL
            (( $? != RC_SUCCESS )) && rc=$RC_INCORRECT_INPUT
        fi
    else
        cpu_usage_monitor_interval=10
    fi

    #======================================================================
    : Create the application server if no input errors have been detected
    #======================================================================
    if (( $rc == RC_UNKNOWN )); then

        [[ -n $startup_mode ]] && startup_mode=" -O $startup_mode"
        if [[ -n $monitors ]]; then
            print -- "$0()[$LINENO]($SECONDS): $HAUTILS/claddserv -s $appname -b \"$start_script\" -e \"$stop_script\" -m \"$monitors\"$startup_mode -C \"$process_to_monitor_cpu\" -i \"$cpu_usage_monitor_interval\" -E \"$cpu_usage_monitor\"" >>$CLMGR_TMPLOG  # Always log commands
            $HAUTILS/claddserv -s $appname \
                -b "$start_script" \
                -e "$stop_script" \
                -m "$monitors"$startup_mode \
                -C "$process_to_monitor_cpu" \
                -i $cpu_usage_monitor_interval \
                -E "$cpu_usage_monitor"
        else
            print -- "$0()[$LINENO]($SECONDS): $HAUTILS/claddserv -s $appname -b \"$start_script\" -e \"$stop_script\"$startup_mode -C \"$process_to_monitor_cpu\" -i \"$cpu_usage_monitor_interval\" -E \"$cpu_usage_monitor\"">>$CLMGR_TMPLOG  # Always log commands
            $HAUTILS/claddserv -s $appname \
                -b "$start_script" \
                -e "$stop_script"$startup_mode \
                -C "$process_to_monitor_cpu" \
                -i $cpu_usage_monitor_interval \
                -E "$cpu_usage_monitor"
        fi
        rc=$?
        print "claddserv RC: $rc" >>$CLMGR_TMPLOG  # Always log command result

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

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