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

##
## NAME:    cl_sapStop
##
## PURPOSE:
##          Stop script for SAP NetWeaver instance(s).
##
##
## ARGUMENTS:
##
##  Type:
##      -a Application ID
##
##
## OUTPUT:
## 
## 
## RETURNS:
##      0 
##
. /usr/es/lib/ksh93/func_include
typeset version="1.10"

#----------------------------------------------------------------------------
# Global Definitions
#----------------------------------------------------------------------------
. /usr/es/sbin/cluster/sa/sap/etc/SAPGlobals
. /usr/es/sbin/cluster/sa/sap/sbin/SAPUtilities

# Including Availability metrics library file
. /usr/es/lib/ksh93/availability/cl_amlib

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

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

typeset script_name="cl_sapStop"
typeset -i rc=0
typeset -i mycnt=0
typeset -i count=0
typeset -i ctl=0

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
       ((ctl=count-1))
       if (( $ctl >= 0 ))
       then
          virt_ips[$count]=${virt_ips[$ctl]}
       fi
    fi

    [[ ${is_nfs} == 1 ]] && {
    APP_ID=$(clodmget -n -q "name=INSTANCE_NAMES and value=${inst_names[$count]}" -f application_id HACMPsa_metadata)
    RG=$(clodmget -n -q "application_id=$APP_ID and name=RESOURCE_GROUP" -f value HACMPsa_metadata)
    amlog_trace $AM_SA_SAP_STOP_BEGIN "SAP NFS Availability check|$RG"
    KLIB_SAP_SA_logmsg DEBUG 151 1 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - has its SAP Global filesystem on a NFS based share.\n Availability is evaluated now.\n"  $script_name ${inst_names[$count]} $SID
    Check_NFS_Service -V ${nfs_ip} -M ${sapmnt_nfs}
    [[ $? == $ERROR ]] && {
        [[ ${inst_names[$count]} != @(ERS*) ]] && {
            Kill_instance -N -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"
            KLIB_SA_logmsg DEBUG 151 85 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance finshed manual cleanup.\n"  $script_name ${inst_names[$count]} $SID
            amlog_err $AM_SA_SAP_STOP_FAILURE "SAP NFS Availability check|$RG"
        }
    exit 0
    }
    amlog_trace $AM_SA_SAP_STOP_END "SAP NFS Availability check|$RG"
    }
  
  # Format for consumption by cl_availability utility
  APP_ID=$(clodmget -n -q "name=INSTANCE_NAMES and value=${inst_names[$count]}" -f application_id HACMPsa_metadata)
  RG=$(clodmget -n -q "application_id=$APP_ID and name=RESOURCE_GROUP" -f value HACMPsa_metadata)
  amlog_trace $AM_SA_SAP_STOP_BEGIN "Stop SAP instance|$RG"
  
  #ensure sapstartsrv is started or can be started otherwise clean up manually for none ers instances and exit 0     
  Control_sapstartsrv -A "Prereq_and_start_cmd" -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"
  typeset -i rc_control_sapstartsrv_Prereq_and_start_cmd=$?    

  #sapstartsrv can not be used. Force a cleanup for none ERS instances    
  [[ $rc_control_sapstartsrv_Prereq_and_start_cmd == $sapstartsrv_failed_to_start ]] && {
    KLIB_SA_logmsg ERROR 151 80 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The sapstartsrv process failed to start.\n The instance and its sapstartsrv process will be manually cleand up.\n The instance Type ERS will not be stopped.\n"  $script_name ${inst_names[$count]} $SID
    [[ ${inst_names[$count]} != @(*ERS*) ]] && Kill_instance -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"
    #Here no kill for ERS instances is required. This would destroy all replicated enqueues
    Control_sapstartsrv -A "Kill" -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"
    KLIB_SA_logmsg INFO 151 81 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance and its sapstartsrv is manually cleand up. ERS processes will be still running. \n"  $script_name ${inst_names[$count]} $SID
  } 
    
  # sapstartsrv is used to stop     
  [[ $rc_control_sapstartsrv_Prereq_and_start_cmd == $sapstartsrv_running ]] && {
     KLIB_SA_logmsg INFO 151 82 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The sapstartsrv process is running. Stop the instance using sapcontrol.\n"  $script_name ${inst_names[$count]} $SID
     [[ ${inst_names[$count]} != @(ERS*) ]] && { 
       KLIB_SA_logmsg INFO 151 83 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance is not of Type ERS. Stop instance now.\n"  $script_name ${inst_names[$count]} $SID
       Control_instance -A "Stop" -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}" -T "0"
       [[ $? != $sapcontrol_0 ]] && {
         KLIB_SA_logmsg ERROR 151 84 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance failed to stop using sapcontrol -function Stop. \n Instance will be cleaned up manually.\n"  $script_name ${inst_names[$count]} $SID
         Kill_instance -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"
         KLIB_SA_logmsg DEBUG 151 85 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance finshed manual cleanup.\n"  $script_name ${inst_names[$count]} $SID
       } || {
         #if we are running on a shared vg we must wait until the instance has stopped to ensure all executables remain available until completion.
         [[ $is_local_vg == "0" ]] && { 
           ${su_sapadm} ${SAPenv} ${sap_exe_dir[$count]}/sapcontrol -nr ${inst_numbers} -function WaitforStopped ${wait_for_stopped_timeout} ${WaitforStopped_delay}
         }
       }
     }
     KLIB_SAP_SA_logmsg DEBUG 151 86 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - Now stop sapstartsrv process. \n"  $script_name ${inst_names[$count]} $SID
     Control_sapstartsrv -A "Stop" -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"    
     [[ $? != $sapcontrol_0  ]] && {
       KLIB_SAP_SA_logmsg ERROR 151 87 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance's sapstartsrv process failed to stop using sapcontrol -function StopService. \n Sapstartsrv will be cleaned up manually.\n"  $script_name ${inst_names[$count]} $SID
       Control_sapstartsrv -A "Kill" -I ${inst_names[$count]} -S ${SAPSYSTEMNAME} -E ${sap_exe_dir[$count]} -V ${virt_ips[$count]} -L "${SAPenv}"
       amlog_err $AM_SA_SAP_STOP_FAILURE "Stop SAP instance|$RG"
     }     
     KLIB_SAP_SA_logmsg INFO 151 88 sapsa.cat "\"%1\$s\" Instance \"%2\$s\" of \"%3\$s\" - The instance and its sapstartsrv are stopped.\n"  $script_name ${inst_names[$count]} $SID
     amlog_trace $AM_SA_SAP_STOP_END "Stop SAP instance|$RG"
   }

((count=count+1))
done
exit 0
