#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2019,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r720 src/43haes/usr/sbin/cluster/sa/sap/sbin/cl_sapERSrelocateMonitor.sh 1.8 
#   
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2013,2015 
# 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/sap/sbin/cl_sapERSrelocateMonitor.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM
##
## NAME:    cl_sapERSrelocateMonitor
##
## PURPOSE:
##          Monitor script for SAP NetWeaver ERS instance(s).
##
##
## ARGUMENTS:
##
##  Type:
##      -a Application ID
##
##
## OUTPUT:
## 
## 
## RETURNS:
##      0 on no corresponding CS is running or starting
##      1 on detection of an corresponding starting/running CS instance
##
. /usr/es/lib/ksh93/func_include

#----------------------------------------------------------------------------
# Global Definitions
#----------------------------------------------------------------------------

. /usr/es/sbin/cluster/sa/sap/etc/SAPGlobals
. /usr/es/sbin/cluster/sa/sap/sbin/SAPUtilities

typeset PROGRAM=${0##*/}
PATH=$PATH:/usr/es/sbin/cluster/sa/sbin
PATH=$PATH:/usr/es/sbin/cluster/utilities
PATH=$PATH:/bin:/usr/bin
export PATH

#-------------------------------------------------------------------------------
#Main
#-------------------------------------------------------------------------------

eval export $(cllsparam -n $(clodmget -f nodename HACMPcluster))

if [[ $VERBOSE_LOGGING == 'high' ]]
then
    PS4_TIMER=true
    set -x
    version='1.8'
fi
typeset script_name="cl_sapERSrelocateMonitor"

typeset -i rc=0
typeset -i mycnt=0
typeset -i count=0
typeset -i enq2=0
typeset enqrep_process=""

if [[ -z $ODMDIR ]]; then
    ODMDIR=/usr/es/sbin/cluster/etc/objrepos/active/
fi
export ODMDIR

while getopts a: option
do
    case $option in
    a)
        APPLICATION_ID=$OPTARG
    ;;
    esac
done

[[ -z $APPLICATION_ID ]] && {
    KLIB_SAP_SA_logmsg ERROR 151 73 sapsa.cat "\"%1\$s\": Application ID not passed as input Parameter. Quit immediately with Exit code 1. Please add application ID as input parameter to the PowerHA Smart Assist Application Servers.\n" $script_name
    exit 1
}

# Define an array of instances from application_ID and get the appropriate SID from ODM.
typeset myinst_names=$(clodmget -n -q "application_id=$APPLICATION_ID and name=INSTANCE_NAMES" -f value HACMPsa_metadata 2>/dev/null)

[[ -z $myinst_names ]] && {
    KLIB_SAP_SA_logmsg ERROR 151 74 sapsa.cat "clodmget failed to get value of %1$s.\n" "INSTANCE_NAMES"
    exit 1
}
myinst_names=$(echo $myinst_names | awk '{gsub("\n"," ");print $0}')
# For PHA 712 Style ODM entries like --> "ASCS00_SCS01"
myinst_names=$(echo $myinst_names | awk '{gsub("_"," ");print $0}')

for  i  in $myinst_names
do
   inst_names[$mycnt]=$i
   ((mycnt=mycnt+1))
done


. /usr/es/sbin/cluster/sa/sap/sbin/SAPUtilities_xplatform

while (( $count < ${#inst_names[@]} ))
do

    unset SAPSYSTEMNAME
    setSAPGlobalEnv -i ${inst_names[$count]}
    ret=$?
    (( $ret != 0 )) && {
      KLIB_SAP_SA_logmsg ERROR 151 72 sapsa.cat "\"%1\$s\": Environment setup failed. Quit immediately with Exit code 1.\n" $script_name
      exit 1
    }
. /usr/es/sbin/cluster/sa/sap/etc/SAPInstanceGlobals

    if [[ -z ${virt_ips[$count]} ]]
    then
        virt_ips[$count]=${virt_ips[$count-1]}
    fi

   ERS_RG=$(clodmget -n -q "application_id=$APPLICATION_ID and name=RESOURCE_GROUP" -f value HACMPsa_metadata)
   CS=$(clodmget -n -q "group=$ERS_RG and name=MISC_DATA" -f value HACMPresource)
   CS_IPs=$(echo $CS | cut -f2 -d,)
   CS_IP1=$(echo $CS_IPs | cut -f1 -d_)
   CS_IP2=$(echo $CS_IPs | cut -f2 -d_)
   if [[ -n $CS_IP2 ]];then
        CS_IP="${CS_IP1}|${CS_IP2}"
   else
        CS_IP="${CS_IP1}"
   fi
   #if CS ip is aquiring we need to invest
   [[ $(ifconfig -a | egrep -w "${CS_IP}") ]] && { 
     CS_NAME=$(echo $CS | cut -f1 -d,)
     KLIB_SAP_SA_logmsg DEBUG 151 67 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - Found the service IP alias of \"%4\$s\". No er process restart from now.\n" $script_name ${inst_names[$count]} ${SID} ${CS_NAME} 
     
     #Relocation monitor should exit with failure, when both ERS and SCS instances are on same node and Enquque replicator2 is enabled,
     #so that RG will go to error state and it may try on other active node

     instance=${inst_names[$count]}
     INSTANCE_TYPE=${instance%[0-9][0-9]}
     INSTANCE_NO=${instance#${INSTANCE_TYPE}}

     # Get the process name based on the enqueue replicator type
     /usr/bin/su - $SAPADMNUSR -c "env LANG=C  sapcontrol -nr ${INSTANCE_NO} -function GetProcessList" | tr -s ' ' '' | tr -d ' ' | tr ',' ' ' | while read name description rest
     do
       if [[ $description == "EnqueueReplicator" ]]
       then
           # call ensmon with PROFILENAME as parameter. option 2
           /usr/bin/su - $sapadmuser -c "${LAN} ${sap_exe_dir[$count]}/ensmon pf=${instance_prof} 2"
           rc=$?
           enqrep_process="er."
           break
       elif [[ $description == "EnqueueReplicator2" ]]
       then
           # call enq_admin with PROFILENAME as parameter to get the replication status
           /usr/bin/su - $sapadmuser -c "${LAN} ${sap_exe_dir[$count]}/enq_admin --replication_state pf=${instance_prof}"
           rc=$?
           enq2=1
           enqrep_process="enqr."
           break
       fi
     done

     if [[ -z $enqrep_process ]]
     then
         KLIB_SAP_SA_logmsg ERROR 151 89 sapsa.cat "\"%1\$s\" Unable to identify the enqueue replicator type for the instance \"%2\$s\".\n" $script_name ${inst_names[$count]}
         exit 1
     fi

     if (( $rc == 0 )) && (( $enq2 == 1 ))
     then
         #Enqueue replicator2, both ERS and SCS instances are online on the same node, we need to exit with failure for ENQ2
         KLIB_SAP_SA_logmsg INFO 151 90 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - Start moving ERS away from here.\n" $script_name ${inst_names[$count]} ${SID} ${CS_NAME}
         exit 1
     fi

     #the ers is now stopped by en. Now we can remove the filesystem 
     [[ $(ps -fu $sapadmuser | grep "$enqrep_process" | grep ${inst_names[$count]}) ]] || { 
       KLIB_SAP_SA_logmsg INFO 151 68 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - Start to move ERS away after the Instance \"%4\$s\" took over the replication table.\n" $script_name ${inst_names[$count]} ${SID} ${CS_NAME}
       exit 1
     }
   }
((count=count+1))
done
exit 0
