#!/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_delete_node.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM

# 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_delete_node

=head1 VERSION

 Version Number:  1.2
 Last Extracted:  2/10/17 20:08:09
 Last Changed:    11/4/16 09:17:51

 Path, Component, Release(, Level):
 src/43haes/lib/ksh93/hacmp/KLIB_HACMP_delete_node.sh, powerha, 61aha_r722

=head1 SYNOPSIS

clmgr delete node {<node>[,<node#2>,<node#n>,...] | ALL}

=head1 DESCRIPTION

Deletes one or more nodes from the cluster configuration.
If the specified node(s) are assigned to a site, then they
are first removed from that site, then deleted.

=head1 ARGUMENTS

 1. nodes [REQUIRED] [string]
    One or more (comma or space separated) nodes to
    attempt to delete (specified as node labels).

=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.


#============================================================================
#
# Name:        KLIB_HACMP_delete_node
#
# Description: This is the main, FPATH function that is invoked by clmgr
#              to remove a node from the cluster configuration. If
#              just one node is removed, and other nodes remain, then
#              the node is removed from the SystemMirror definitions only,
#              but not CAA. The CAA removal will occur when a synchronization
#              is performed, at which time the other nodes in the cluster
#              will also be notified of the removal, and updated accordingly.
#
# Inputs:      See the "devDoc()" function, above.
#
# Outputs:     None.
#
# Returns:     Zero if no errors are detected. Otherwise, an appropriate
#              non-zero value is returned. Refer to the "RETURN" section
#              of the "devDoc()" function, above, for the standard return
#              code values/meanings for clmgr.
#
#============================================================================
function KLIB_HACMP_delete_node {
    LINENO=2 . $HALIBROOT/log_entry "$0()" "$CL"
    : version=@(#)  7d4c34b 43haes/lib/ksh93/hacmp/KLIB_HACMP_delete_node.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM
    : INPUTS: $*

    typeset nodes=${1//\"/}
            nodes=${nodes//,/ }

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

    #===================================
    : Declare and initialize variables
    #===================================
    integer rc=$RC_UNKNOWN i=0
    typeset node=""

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

    #=================
    : Validate input
    #=================
    elif [[ -z $nodes ]]; 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

    else
        typeset -u uctext=$nodes
        if [[ $uctext == "ALL" ]]; then
            nodes=
            typeset available
            CL=$LINENO KLIB_HACMP_list_nodes available
            for (( i=0; i<${#available[*]}; i++ )); do
                nodes="$nodes ${available[$i]}"
            done

            if [[ $nodes == *([[:space:]]) ]]; then
                /usr/bin/dspmsg -s $CLVT_SET $CLVT_MSGS 328 "Warning: there are no nodes to delete.\n"
                rc=$RC_SUCCESS
            fi

        else
            for node in $nodes; do
                CL=$LINENO KLIB_HACMP_is_known_node "$node" >/dev/null 2>&1
                if (( $? != RC_SUCCESS )); then
                    typeset MSG=$(/usr/bin/dspmsg -s $CLVT_SET $CLVT_MSGS 102 "\nERROR: \"%1\$s\" does not appear to exist!\n\n" "$node")
                    MSG=${MSG##+([[:space:]])}
                    print -u2 "${MSG%%+([[:space:]])}"
                    rc=$RC_NOT_FOUND
                fi
            done

            if (( rc == RC_NOT_FOUND )); then
                print -u2 ""
                /usr/bin/dspmsg -s $CLVT_SET $CLVT_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
            fi
        fi
    fi

    #=======================================================================
    : Validate if given node is offline. If any node is online, we exit.
    #=======================================================================
    if (( $rc == RC_UNKNOWN ))
    then
        for tempnode in $nodes
        do
            #
            :   Find what nodes $tempnode thinks is active
            #
            clgetactivenodes -n $tempnode 2>/dev/null 1>&2
            returncode=$?
            #
            :   clgetactivenodes return code is the number of active nodes,
            :   or -1 or 255 in case of an error
            #
            if (( $returncode == 255 || $returncode == 0 ))
            then
                continue          # $tempnode has no clue about active nodes
            else
                dspmsg -s $CLMGR_SET $CLMGR_MSGS 351 "\nERROR: cluster services on one or more of the specified nodes, \"%1\$s\", are in a state that prevent the cluster configuration from being removed. A cluster cannot be deleted from a node while cluster services remain active. Please consider running \"%2\$s offline node <NODE>\" for each active node.\n" "$nodes" "$CLMGR_PROGNAME" 1>&2
                rc=$RC_ERROR      # Should have an active node list. Mark as error.
                break
            fi
        done
    fi

    #=======================================================================
    : Validates if any system mg exists with this node ID, if yes then
    : stop here
    #=======================================================================
    if (( $rc == RC_UNKNOWN )); then
        for node in $nodes; do
            is_entry=$($HAUTILS/clodmget -n -q "field_type=NODE and value=$node" -f identifier HACMPxd_ext_attr 2>/dev/null)
            if [[ -n $is_entry ]]; then
                rc=$RC_ERROR
                /usr/bin/dspmsg -s $CLVT_SET $CLVT_MSGS 769 "\nA system mirror group with name \"%1\$s\" exists for node \"%2\$s\". Please remove it first.\n\n" "$is_entry" "$node" 1>&2
                break
            fi
        done
        (( $rc != RC_SUCCESS )) && print -u2
    fi

    #========================================================
    : Delete the node if no input errors have been detected
    #========================================================
    if (( $rc == RC_UNKNOWN )); then
        for node in $nodes; do
            CL=$LINENO cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 307 "Attempting to delete node \"%1\$s\" from the cluster...\n" "$node"
            print -- "$0()[$LINENO]($SECONDS): $HAUTILS/clnodename -r \"$node\"" >>$CLMGR_TMPLOG  # Always log commands
            $HAUTILS/clnodename -r "$node"
            rc=$?
            print "clnodename RC: $rc" >>$CLMGR_TMPLOG  # Always log command result
            if (( $rc != RC_SUCCESS )); then
                rc=$RC_ERROR
                /usr/bin/dspmsg -s $CLVT_SET $CLVT_MSGS 300 "\nERROR: failed to delete \"%1\$s\".\n\n" "$node" 1>&2
                CL=$LINENO cl_dspmsg -s $CLVT_SET $CLVT_MSGS 9999 'Use the "lssrc -ls clstrmgrES" command on node "%1$s" to ensure that PowerHA SystemMirror cluster services are not running. Also, remove node "%1$s" from all resource groups, site definitions, collocation and anticollocation lists.\n' "$node" 1>&2
                break
            fi
        done

        (( $rc != RC_SUCCESS )) && print -u2
    fi

    #=======================================================================
    : If a user input error was detected, provide some helpful suggestions
    #=======================================================================
    if (( $rc == RC_MISSING_INPUT || $rc == RC_INCORRECT_INPUT )) && \
       [[ $CLVT_GUI == *([[:space:]]) ]]
    then
        CL=$LINENO cl_dspmsg -s $CLVT_SET $CLVT_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" \
        "delete node -h" "NODE:" "$CLVT_PROGNAME" 1>&2
    fi

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