#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2017,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# @(#)  7d4c34b 43haes/lib/ksh93/hacmp/KLIB_HACMP_add_method.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_method

=head1 VERSION

 Version Number:  1.5
 Last Extracted:  1/31/14 04:41:03
 Last Changed:    8/6/13 16:54:54

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

=head1 SYNOPSIS

 clmgr add method <method_label> \
             TYPE=snapshot \
             FILE=<executable_file> \
             [ DESCRIPTION=<description> ]
 clmgr add method <method_label> \
             TYPE=verify \
             FILE=<executable_file> \
             [ SOURCE={script|library} ] \
             [ DESCRIPTION=<description> ]

 clmgr add method <method_label> \
             TYPE=notify \
             DESCRIPTION=<description> \
             FILE=<executable_file> \
             CONTACT=<number_to_dial_or_email_address> \
             EVENTS=<event>[,<event#2>,<event#n>,...] \
             [ NODES=<node>[,<node#2>,<node#n>,...] ] \
             [ RETRY=<retry_count> ] \
             [ TIMEOUT=<timeout> ]

 NOTE: the alias for "method" is "me".

=head1 DESCRIPTION

Attempts to create a new method within the cluster
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. name [REQUIRED] [string]
    The label that is to be given to this method.

 3. type [REQUIRED] [set]
    The type of method to be created.

    Valid values: {notify|snapshot|verify}

 4. desc [OPTIONAL] [string]
    A description of the method. If no description is provided,
    then one will be automatically generated.

 5. file [REQUIRED] [abspath]
    An executable file that will be invoked by this method.

 6. contact [REQUIRED FOR NOTIFY] [string]
    The contact information. Might be an email address, pager number, etc...

 7. events [REQUIRED FOR NOTIFY] [string]
    The event(s) to provide notification about (i.e. when that event occurs).

 8. nodes [OPTIONAL FOR NOTIFY] [string]
    The nodes that the notification will be sent from, in priority order.

 9. retry [OPTIONAL FOR NOTIFY] [posint]
    The number of times to attempt to send the notification before giving up.

 10. timeout [OPTIONAL FOR NOTIFY] [posint]
    The maximum number of seconds to attempt each notification before giving up.

 11. source [OPTIONAL FOR VERIFY] [set]
    The type of file containing the verification logic, and executable file
    (e.g. "script"), and a dynamic loadable library (e.g. "library").

    Valid values: {script|library}

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

    typeset -n properties=$1
    typeset name=${2//\"/}
    typeset -l type=${3//\"/}
    typeset desc=${4//\"/}
    typeset file=${5//\"/}
    typeset contact=${6//\"/}    # Notify methods only
            contact=${contact//,/ }
    typeset events=${7//\"/}     # Notify methods only
    typeset nodes=${8//\"/}      # Notify methods only
    typeset retry=${9//\"/}      # Notify methods only
    typeset timeout=${10//\"/}   # Notify methods only
    typeset -l source=${11//\"/} # Verify methods only

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

    #===================================
    : Declare and initialize variables
    #===================================
    typeset -i rc=$RC_UNKNOWN
    [[ $desc == *([[:space:]]) ]] && eval desc=$file
    if [[ $file == *([[:space:]]) && \
          $type == no* && \
          -f /usr/es/sbin/cluster/samples/pager/sample.txt ]]
    then
        file=/usr/es/sbin/cluster/samples/pager/sample.txt
    fi

    #=================================================================
    : This is the list of supported events that is currently hard-
    : coded into "clissuepage.c". The current utilities do not do an
    : adequate job of explaining that other events will not work, so
    : we have to provide that service here.
    #=================================================================
    typeset SUPPORTED_EVENTS="
        node_up                      node_down
        node_up_complete             node_down_complete
        node_up_local                node_down_local
        node_up_local_complete       node_down_local_complete
        node_up_remote               node_down_remote
        node_up_remote_complete      node_down_remote_complete

        site_up                      site_down
        site_up_complete             site_down_complete
        site_up_local                site_down_local
        site_up_local_complete       site_down_local_complete
        site_up_remote               site_down_remote
        site_up_remote_complete      site_down_remote_complete

        network_up                   network_down
        network_up_complete          network_down_complete
        swap_adapter                 
        swap_adapter_complete        
        acquire_service_addr
        acquire_takeover_addr        cluster_notify
        config_too_long              event_error
        external_resource_state_change      external_resource_state_change_complete
        fail_interface               
        forced_down_too_long
        get_disk_vg_fs               intersite_fallover_prevented
        join_interface
        reconfig_configuration_complete     reconfig_resource_acquire
        reconfig_resource_acquire_fence     reconfig_resource_acquire_secondary
        reconfig_resource_complete          reconfig_resource_complete_secondary
        reconfig_resource_release           reconfig_resource_release_fence
        reconfig_resource_release_primary   reconfig_resource_release_secondary
        reconfig_topology_complete          reconfig_topology_start
        release_vg_fs
        release_service_addr         release_takeover_addr
        rep_disk_notify
        resource_state_change        resource_state_change_complete
        rg_move                      rg_move_acquire
        rg_move_complete             rg_move_fence
        rg_move_release
        server_down                  server_down_complete
        server_restart               server_restart_complete
        site_isolation               site_isolation_complete
        site_merge                   site_merge_complete
        split_merge_prompt           start_server
        start_udresource             stop_server
        stop_udresource
"

    #=================
    : Validate input
    #=================
    if [[ $name == *([[:space:]]) ]]; 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 [[ -n $name && -n "${name//[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" "$name" "${name//[a-zA-Z0-9_]/}" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ $type == *([[:space:]]) ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 101 "\nERROR: this operation requires the \"%1\$s\" attribute.\n\n" TYPE 1>&2
        rc=$RC_MISSING_INPUT

    elif [[ $type != @(sn|ve|no)* ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 110 "\nERROR: invalid value specified for \"%1\$s\":  \"%2\$s\".\n" TYPE "$type" 1>&2
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 "Valid values: %1\$s\n\n" "notify, snapshot, verify" 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    if [[ $file == *([[:space:]]) ]]; then
        /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 101 "\nERROR: this operation requires the \"%1\$s\" attribute.\n\n" FILE 1>&2
        rc=$RC_MISSING_INPUT

    elif [[ ! -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

    #
    : NOTIFY-only validation
    #
    if [[ $type == no* ]]; then
        if [[ $contact == *([[:space:]]) ]]; then
            /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 101 "\nERROR: this operation requires the \"%1\$s\" attribute.\n\n" CONTACT 1>&2
            rc=$RC_MISSING_INPUT
        fi

        if [[ $events == *([[:space:]]) ]]; then
            /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 101 "\nERROR: this operation requires the \"%1\$s\" attribute.\n\n" EVENTS 1>&2
            /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 "Valid values: \n%1\$s\n\n" "$SUPPORTED_EVENTS" 1>&2
            rc=$RC_MISSING_INPUT
        fi

        if [[ $retry != *([[:space:]]) && $retry != +([[:digit:]]) ]]; then
            /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 111 "\nERROR: \"%1\$s\" requires a positive, integer value.\n\n" RETRY 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ $timeout != *([[:space:]]) && $timeout != +([[:digit:]]) ]]; then
            /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 111 "\nERROR: \"%1\$s\" requires a positive, integer value.\n\n" TIMEOUT 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        events=${events//,/ }
        for event in $events; do
            if [[ " $SUPPORTED_EVENTS " != *+([[:space:]])$event+([[:space:]])* ]]
            then
                /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 216 "\nERROR: event \"%1\$s\" is not currently supported for\n       notification methods.\n\n" 1>&2
            /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 "Valid values: \n%1\$s\n\n" "$SUPPORTED_EVENTS" 1>&2
                rc=$RC_INCORRECT_INPUT
            fi
        done

        if [[ $nodes == *([[:space:]]) ]]; then
            nodes=$LOCAL_NODE
        else
            #
            : If nodes were specified, verify that they are known nodes.
            #
            typeset checked=
            typeset -i all_nodes_found=1
            for node in ${nodes//,/ }; do
                [[ " $checked " == *\ $node\ * ]] && continue

                checked="$checked $node"
                CL=$LINENO KLIB_HACMP_is_known_node "$node" >/dev/null 2>&1
                if (( $? != RC_SUCCESS )); then
                    rc=$RC_INCORRECT_INPUT
                    all_nodes_found=0
                    /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 102 "\nERROR: \"%1\$s\" does not appear to exist!\n\n" "$node" 1>&2
                fi
            done

            if (( ! all_nodes_found )); then
                /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 151 "Available Nodes:\n\n" 1>&2
                typeset available
                CL=$LINENO KLIB_HACMP_list_nodes available
                for (( i=0; i<${#available[*]}; i++ )); do
                    if [[ ${available[$i]} != *([[:space:]]) ]]; then
                        print -u2 "\t${available[$i]}"
                    fi
                done
                print -u2 ""
            fi

            if [[ $nodes == *+([[:space:]])* ]]; then
                nodes=${nodes//+([[:space:]])/,}
            fi
        fi

    else
        if [[ $contact != *([[:space:]]) ]]; then
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 45 '\nERROR: "%1$s" may only be used with "%2$s".\n\n' CONTACT TYPE=notify 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ $events != *([[:space:]]) ]]; then
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 45 '\nERROR: "%1$s" may only be used with "%2$s".\n\n' EVENTS TYPE=notify 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ $nodes != *([[:space:]]) ]]; then
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 45 '\nERROR: "%1$s" may only be used with "%2$s".\n\n' NODES TYPE=notify 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ $retry != *([[:space:]]) ]]; then
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 45 '\nERROR: "%1$s" may only be used with "%2$s".\n\n' RETRY TYPE=notify 1>&2
            rc=$RC_INCORRECT_INPUT
        fi

        if [[ $timeout != *([[:space:]]) ]]; then
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 45 '\nERROR: "%1$s" may only be used with "%2$s".\n\n' TIMEOUT TYPE=notify 1>&2
            rc=$RC_INCORRECT_INPUT
        fi
    fi

    #
    : VERIFY-only validation
    #
    if [[ $type == ve* ]]; then
        if [[ $source == *([[:space:]]) ]]; then
            source=" -m 0"
        else
            case $source in
                @(s|f)*) source=" -m0" ;;
                     l*) source=" -m1" ;;
                      *) /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 110 '\nERROR: invalid value specified for "%1$s":  "%2$s".\n' SOURCE "$source" 1>&2
                         /usr/bin/dspmsg -s $CLMGR_SET $CLMGR_MSGS 3 'Valid values: %1$s\n\n' "script, library" 1>&2
                         rc=$RC_INCORRECT_INPUT
            esac
        fi

    elif [[ $source != *([[:space:]]) ]]; then
        CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 45 '\nERROR: "%1$s" may only be used with "%2$s".\n\n' SOURCE TYPE=verify 1>&2
        rc=$RC_INCORRECT_INPUT
    fi

    #==========================================================
    : Create the method if no input errors have been detected
    #==========================================================
    if (( $rc == RC_UNKNOWN )); then
        #==============================================================
        # NOTE: the "claddcustom" command is... questionably written.
        #       It *requires* no space between the option flags and
        #       their arguments. If any space exists, it will be
        #       treated as a literal part of the argument. ~sigh!
        #==============================================================
        typeset cmd=
        if [[ $type == sn* ]]; then
            cmd="claddcustom"
            print -- "$0()[$LINENO]($SECONDS): $HAUTILS/claddcustom -t snapshot -n\"$name\" -I\"$desc\" -v\"$file\"" >>$CLMGR_TMPLOG  # Always log commands
            $HAUTILS/claddcustom -t snapshot \
                                 -n"$name"   \
                                 -I"$desc"   \
                                 -v"$file"

        elif [[ $type == ve* ]]; then
            cmd="claddcustom"
            print -- "$0()[$LINENO]($SECONDS): $HAUTILS/claddcustom -t verify -n\"$name\" -I\"$desc\" -v\"$file\"$source" >>$CLMGR_TMPLOG  # Always log commands
            $HAUTILS/claddcustom -t verify \
                                 -n"$name" \
                                 -I"$desc" \
                                 -v"$file"$source

        elif [[ $type == no* ]]; then
            cmd="clmkpgr"
            typeset rOpt= tOpt=
            [[ -n $retry ]] && rOpt=" -r$retry"
            [[ -n $timeout ]] && tOpt=" -t$timeout"
            print -- "$0()[$LINENO]($SECONDS): $HAUTILS/clmkpgr -m \"$name\" -d \"$desc\" -n \"$nodes\" -N \"$contact\" -f \"$file\" -e \"$events\"$rOpt$tOpt" >>$CLMGR_TMPLOG  # Always log commands
            $HAUTILS/clmkpgr -m "$name" \
                             -d "$desc" \
                             -n "$nodes" \
                             -N "$contact" \
                             -f "$file" \
                             -e "$events"$rOpt$tOpt
        fi
        rc=$?
        print "$cmd 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" "$name" 1>&2

        #===========================================================
        : If output from this operation was requested, retrieve it
        #===========================================================
        else
            if (( CLMGR_VERBOSE )) || [[ -n $CLMGR_ATTRS ]]; then
                CL=$LINENO KLIB_HACMP_get_method_attributes "$name" "$type" 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 method -h" "METHOD:" "$CLMGR_PROGNAME" 1>&2
    fi

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