#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2019,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r714 src/43haes/usr/sbin/cluster/sa/tsmadmin/sbin/cl_tsm_admin_config.sh 1.4 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 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/usr/sbin/cluster/sa/tsmadmin/sbin/cl_tsm_admin_config.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM

###############################################################################################
#
# NAME:
#       cl_tsm_admin_config
#
# PURPOSE:
#       create PowerHA SystemMirror configuration for TSM admin center. This script configures TSM admin
#       Resource Group with admin Application server and service IP address
#
# ARGUMENTS:
#       -a Application name
#       -p Primary Node
#       -t Takeover Nodes(s)
#       -s Service IP
#       -n Netmask/prefix Length
#	-u TSM admin center user id
#
# RETURNS
#  0 on success
#  1 on Failure
#################################################################################################
typeset version="1.0"
[[ "$VERBOSE_LOGGING" == "high" ]] && set -x
. /usr/es/sbin/cluster/sa/tsmadmin/sbin/cl_tsmadminGlobals
. /usr/es/sbin/cluster/sa/tsmadmin/sbin/cl_tsmadminUtilities

KLIB_HACMPLOG_ENTRY=$KLIB_TSM_ADMIN_HACMPLOG_ENTRY

typeset APPLICATION_ID       # Smart Assist Application Name of the TSM Admin center.
typeset PRIMNODE TAKEOVNODES # primary and takeover nodes.
typeset SERVICE_IP           # Service IP for the TSM admin center
typeset NETMASK              # Netmask/ prefix Length of service IP address.
typeset USERID		     # TSM Admin center user id
typeset PASSWORD	     # TSM Admin center password
typeset MODIFY="N"           # Modify the TSM admin configuration.

typeset SMARTASSIST_ID="TSM_AC" # TSM admin smart assist ID
typeset COMPONENT_ID                  # component ID of TSM admin smart assist

#################################################################################
# Function: addadminInstance
#
# Purpose: To create PowerHA SystemMirror resources and Resource group for Managing
#          TSM admin center.
#
# Arguments: None.
#
# Returns: 0 for Sucess
#          1 for Failure
################################################################################

function addadminInstance      {

        [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
        typeset rgname="TSM_AC_RG_"$APPLICATION_ID
        typeset appname="TSM_AC_APP_"$APPLICATION_ID
        typeset appmonname="TSM_AC_APP_MON_"$APPLICATION_ID

        COMPONENT_ID="TSM_ADMINCENTER"

        KLIB_SA_logmsg INFO 1 20 tsmadminsa.cat "Adding TSM Admin center configuration %1\$s\n" $APPLICATION_ID
        dspmsg -s 1 tsmadminsa.cat 20 "Adding TSM admin center configuration %1\$s\n" $APPLICATION_ID

        rgname=$(getUnusedName $rgname "resource_group")
        [[ "$?" == "1" ]] && {
        KLIB_SA_logmsg ERROR 1 21 tsmadminsa.cat "Unable to get the unused name for %1\$s=%2\$s\n" "resource_group" $rgname
        exit 1
        }

        appname=$(getUnusedName $appname "application")
        [[ "$?" == "1" ]] && {
        KLIB_SA_logmsg ERROR 1 21 tsmadminsa.cat "Unable to get the unused name for %1\$s=%2\$s\n" "application" $appname
        exit 1
        }

        appmonname=$(getUnusedName $appmonname "application_monitor")
        [[ "$?" == "1" ]] && {
        KLIB_SA_logmsg ERROR 1 21 tsmadminsa.cat "Unable to get the unused name for %1\$s=%2\$s\n" "application_monitor" $appmonname
        exit 1
        }
	
	isServiceIPLabelAlreadyDefined $SERVICE_IP
        [[ "$?" == "0" ]] && {
        KLIB_SA_logmsg ERROR 1 22 tsmadminsa.cat "service label %1\$s already defined in the PowerHA SystemMirror configuration\n" $SERVICE_IP
        exit 1
        }

        #Adding service IP label
        addServiceIPLabel

	#creating Resource Group for TSM Admin center configuration
        dspmsg -s 1 tsmadminsa.cat 27 "Adding TSM Admin center Resource Group %1\$s to PowerHA SystemMirror configuration\n" $rgname
        KLIB_SA_logmsg INFO 1 27 tsmadminsa.cat "Adding TSM admin center Resource Group %1\$s to PowerHA SystemMirror configuration\n" $rgname
        claddgrp -g "$rgname" -n "$PRIMNODE $TAKEOVNODES" \
                -S "OHN" -O "FNPN" -B "FBHPN" \
                -K $APPLICATION_ID

        (( $? != 0 )) && {
                          KLIB_SA_logmsg ERROR 1 28 tsmadminsa.cat "Failed while adding TSM admin center Resource Group %1\$s\n" $rgname
                          exit 1
                        }

        #creating TSM admin center Application

        startscript="$TSM_AC_HA_SBIN/cl_tsmadminstart"
        stopscript="$TSM_AC_HA_SBIN/cl_tsmadminstop -a $APPLICATION_ID"
        monitorscript="$TSM_AC_HA_SBIN/cl_tsmadminmonitor -a $APPLICATION_ID"

        KLIB_SA_logmsg INFO 1 29 tsmadminsa.cat "Adding TSM Admin center Application %1\$s to PowerHA SystemMirror configuration\n" $appname

        clvt add application $appname \
             STARTSCRIPT="$startscript" \
             STOPSCRIPT="$stopscript" >/dev/null 2>&1 || {
                                          KLIB_SA_logmsg ERROR 1 30 tsmadminsa.cat "Failed while adding TSM admin center Application %1\$s\n" $appname
                                               exit 1
                                        }

        KLIB_SA_logmsg INFO 1 31 tsmadminsa.cat "Adding TSM Admin center Application monitor %1\$s to PowerHA SystemMirror configuration\n" $appmonname

        claddappmon name=$appmonname \
          MONITOR_TYPE='user' \
          RESOURCE_TO_MONITOR=$appname \
          INVOCATION='longrunning' \
          FAILURE_ACTION='fallover' \
          RESTART_METHOD="$startscript" \
          CLEANUP_METHOD="$stopscript" \
          MONITOR_METHOD="$monitorscript" \
          MONITOR_INTERVAL='120' \
          HUNG_MONITOR_SIGNAL='9' \
          STABILIZATION_INTERVAL='180' \
          RESTART_COUNT='3' \
          RESTART_INTERVAL='900' >/dev/null 2>&1 || {
                                      KLIB_SA_logmsg ERROR 1 32 tsmadminsa.cat "Failed while adding TSM Admin center Application monitor %1\$s\n" $appmonname
                                      exit 1
                                      }


        # Add service IP, Application to Resource Group
        KLIB_SA_logmsg INFO 1 41 tsmadminsa.cat "Modifying TSM admin center Resource Group %1\$s\n" $rgname
        clvt modify resource_group "$rgname" \
        SERVICE_LABEL="$SERVICE_IP" \
        APPLICATIONS="$appname" >/dev/null 2>&1 || {
                                          KLIB_SA_logmsg ERROR 1 42 tsmadminsa.cat "Failed while modifying TSM admin center Resource Group %1\$s\n" $rgname
                                          exit 1
                                  }

	
        # Add the entry to HACMPsa_metadata ODM

        KLIB_SA_logmsg INFO 1 33 tsmadminsa.cat "Adding TSM Admin center to ODM\n"
        claddsaapp -a $APPLICATION_ID \
        RESOURCE_GROUP=$rgname \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        APPLICATION_NAME="$APPLICATION_ID" \
	TSM_AC_USER="$USERID" \
        TSM_AC_PASSWORD="$PASSWORD" >/dev/null 2>&1 || {
                                               KLIB_SA_logmsg ERROR 1 34 tsmadminsa.cat "Failed while Adding TSM Admin center confgiuration to ODM\n"
                                               exit 1
                                        }
}

#----------------------------------------------------------------------------
# Function:
#   addServiceIPLabel
#
# Purpose:
#   Adds Service IP label to the PowerHA SystemMirror configuration if
#   it doesn't already exist.
#
# Arguments:
#   n/a
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------
function addServiceIPLabel {
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    typeset results

    #
    # Can the service IP label be resolved?
    #
    /usr/bin/host $SERVICE_IP >/dev/null 2>&1
    (( $? != 0 )) && {
        # The service IP label cannot be resolved
        KLIB_SA_logmsg ERROR 1 23 Tsmadminsa.cat "Service IP label %1\$s can not be resolved\n" $SERVICE_IP
        exit 1
    }
    result=$(clvt query interface | grep $SERVICE_IP)
    [[ -n $result ]] &&
        clvt delete interface $SERVICE_IP

    clvt query service_ip $SERVICE_IP >/dev/null 2>&1
    [[ $? != "0" ]] && { # Create the service IP label
        KLIB_SA_logmsg INFO 1 24 tsmadminsa.cat "creating Service IP label %1\$s\n" $SERVICE_IP

        nodes=$(echo "$PRIMNODE $TAKEOVNODES")

        addr=$(/usr/bin/host $SERVICE_IP|awk '{print $3}'| sed s/,//g)
        isipv6addr $addr
        if [[ "$?" == "0" ]]
        then
                Net_type="2" # Net_type will be specified in HACMPadapter ODM for IPv6=2, IPv4=1
        else
                Net_type="1"
        fi
        network=$(getServiceNetwork $Net_type "$nodes")

        # There are no suitable networks defined to create
        [[ -z $network ]] && {
            KLIB_SA_logmsg ERROR 1 25 tsmadminsa.cat "No suitable PowerHA SystemMirror network is defined to create service IP label\n"
            exit 1
        }

        /usr/es/sbin/cluster/utilities/claddnode -T service -B "$SERVICE_IP" -P "$NETMASK" -w "$network" > /dev/null 2>&1
        (( $? != 0 )) && {
            KLIB_SA_logmsg ERROR 1 26 tsmadminsa.cat "Error while adding service IP label %1\$s to netowk %2\$s\n" $SERVICE_IP $network
            exit 1
        }
    } 

    return 0
}

#################################################################################
# Function: modifyadminInstance
#
# Purpose: To modify PowerHA SystemMirror resources and Resource group for Managing
#          TSM Admin center 
#
# Arguments: None.
#
# Returns: 0 for Sucess
#          1 for Failure
#
################################################################################

function modifyadminInstance      {

        [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
        removeHAresources
        addadminInstance
        return $?
}

#################################################################################
# Function: removeHAresources
#
# Purpose: To remove PowerHA SystemMirror resources and Resource group for Managing
#          TSM Admin center.
#
# Arguments: None.
#
# Returns: 0 for Sucess
#          1 for Failure
#
################################################################################

function removeHAresources      {

        [[ "$VERBOSE_LOGGING" == "high" ]] && set -x

        KLIB_SA_logmsg INFO 1 35 tsmadminsa.cat "Removing TSM Admin center %1\$s from PowerHA SystemMirror configuration\n" $APPLICATION_ID
        rg=$(clodmget -q "name=RESOURCE_GROUP and application_id=$APPLICATION_ID" -f value -n HACMPsa_metadata)
        [[ $? != 0 ]] && {
                                KLIB_SA_logmsg ERROR 1 36 tsmadminsa.cat "Resource Group %1\$s not found in ODM\n" $rg
                                exit 1
                         }

        app_serv=$(clvt query resource_group $rg|grep APPLICATIONS|awk -F= '{ print $2 }' | sed "s/\"//g" )

        for ap_srv in $app_serv
        do
                app_mons=$(clvt query application $ap_srv|grep ASSOCIATEDMONITORS |awk -F= '{ print $2 }' | sed "s/\"//g" )

                #removing the application monitors
                for mon in $app_mons
                do
                        clvt delete application_monitor $mon > /dev/null 2>&1
                        [[ $? != 0 ]] && {
                                KLIB_SA_logmsg ERROR 1 37 tsmadminsa.cat "Failed while deleting Application monitor %1\$s for changing TSM ADMIN center configuration\n" $app_mons
                                exit 1
                        }
                done
        done

        for app in $app_serv;do
                clvt delete application $app > /dev/null 2>&1
                [[ $? != 0 ]] && {
                                        KLIB_SA_logmsg ERROR 1 38 tsmadminsa.cat "Failed while deleting Application for changing TSM Admin center configuration%1\$s\n" $app
                                        exit 1
                                }
        done

        clvt delete resource_group $rg >/dev/null 2>&1
        (( $? != 0 )) && {
                                KLIB_SA_logmsg ERROR 1 39 tsmadminsa.cat "Failed while deleting Resource Group %1\$s for changing TSM Admin center configuration\n" $rg
                                exit 1
                         }
        # Remove the metadata entries
        clrmsaapp -a $APPLICATION_ID >/dev/null 2>&1
        (( $? != 0 )) && {
                                KLIB_SA_logmsg ERROR 1 40 tsmadminsa.cat "Failed while deleting for changing TSM Admin center ODM configuration\n"
                                exit 1
                         }

        return 0
}

	


###########################################
# main
###########################################
export PATH="$(/usr/es/sbin/cluster/utilities/cl_get_path all)"
while getopts a:p:t:s:n:u:m opt
do
        case $opt in
        m) # modifying TSM admin
                MODIFY="Y"
                ;;
        a) # Application Name
                APPLICATION_ID=$OPTARG
                APPLICATION_ID=$(echo $APPLICATION_ID|sed s/*$//) #Remove the trailing whitespaces if any at the end of the string
                KLIB_SA_logmsg INFO 1 10 tsmadminsa.cat "Validating TSM admin Smart Assist application id\n"
                validateAppName "$APPLICATION_ID"
                [[ "$?" == "1" ]] && {
                KLIB_SA_logmsg ERROR 1 11 tsmadminsa.cat "TSM admin smart assist Application id=%1\$s is not in the range [a-z][A-z][0-9]_\n" "$APPLICATION_ID"
                exit 1
                }

                KLIB_SA_logmsg DEBUG 1 12 tsmadminsa.cat "completion of validating TSM admin Smart Assist for applicaton id=%1\$s\n" "$APPLICATION_ID"
                ;;
        p) # Primary node
                PRIMNODE=$OPTARG
                ;;
        t) # Takeover nodes
                TAKEOVNODES=$OPTARG
                ;;
        s) # Service IP of the TSM admin center
                SERVICE_IP=$OPTARG
                ;;
        n) # Netmask/prefix length of the service IP
                NETMASK=$OPTARG
                ;;
	u) # TSM Admin center user id
		USERID=$OPTARG
		;;
	esac
done

#Validate the node names, if there are any Name duplication for Primary and Takeover nodes
#
KLIB_SA_logmsg INFO 1 13 tsmadminsa.cat "Validating TSM admin centerNodes\n"
validateNodes $PRIMNODE "$TAKEOVNODES"
(( $? != 0 )) && {
KLIB_SA_logmsg ERROR 1 14 tsmadminsa.cat "TSM admin center smart assist has primary=%1\$s and takeover nodes=%2\$s as repetitive\n" $PRIMNODE "$TAKEOVNODES"
exit 1
}
# TSM admin password encryption done for specific user
password=$(clmaskpasswd)
checkRC=$?
if (( $checkRC != RC_SUCCESS )); then
    KLIB_SA_logmsg INFO 1 50 tsmadminsa.cat "Failed to set the TSM admin password for user %1\$s\n" $USER
    dspmsg -s 1 tsmadminsa.cat 50 "Failed to set the TSM admin password for user %1\$s\n" $USER
    rc=$RC_ERROR
elif [[ -z $password || $password == *([[:space:]]) ]]; then
    KLIB_SA_logmsg INFO 1 51 tsmadminsa.cat "Invalid password, failed to set the TSM admin password for user %1\$s\n" $USER
    dspmsg -s 1 tsmadminsa.cat 51 "Invalid password, failed to set the TSM admin password for user %1\$s\n" $USER
    rc=$RC_INCORRECT_INPUT
else
    PASSWORD=$(print $password | clencodearg)
fi
KLIB_SA_logmsg DEBUG 1 15 tsmadminsa.cat "completion of validating TSM admin center Smart Assist nodes primary=%1\$s amd takeover nodes=%2\$s\n" $PRIMNODE "$TAKEOVNODES"
if [[ "$MODIFY" == "Y" ]]
then
        KLIB_SA_logmsg INFO 1 16 tsmadminsa.cat "Modify the TSM admin center configuration %1\$s\n" $APPLICATION_ID
        dspmsg -s 1 tsmadminsa.cat 16 " Modifying TSM admin center configuration %1\$s\n" $APPLICATION_ID
        modifyadminInstance
        exit $?
else
        #check If the TSM admin is already configured to PowerHA SystemMirror.

        KLIB_SA_logmsg INFO 1 17 tsmadminsa.cat "Checking if the TSM admin is already configured.\n"
        app_id=$(clodmget -q "name=APPLICATION_NAME" -f application_id -n HACMPsa_metadata)

        [[ $app_id == $APPLICATION_ID ]] &&  {
                        KLIB_SA_logmsg ERROR 1 18 tsmadminsa.cat "TSM admin center with application is %1\$s already configured\n" $APPLICATION_ID
                        exit 1
             }
        KLIB_SA_logmsg DEBUG 1 19 tsmadminsa.cat "TSM admin center with application %1\$s is not already configured\n" $APPLICATION_ID

        addadminInstance
        exit $?
fi
