#!/bin/bash
#############################################################
# Name:        Supportconfig Plugin for SUSE SAP 
# Description: Gathers important troubleshooting information
#              about a SUSE SAP HANA/NetWeaver configurations
# License:     GPLv2
#############################################################

SVER='1.0.4'
RCFILE="/usr/lib/supportconfig/resources/scplugin.rc"
TITLE="SUSE SAP"
INSTANCES=()

[ -s $RCFILE ] && . $RCFILE || { echo "ERROR: Initializing resource file: $RCFILE"; exit 1; }

validate_rpm_if_installed() {
	THISRPM=$1
	echo "#==[ Validating RPM ]=================================#"
	if rpm -q $THISRPM >/dev/null 2>&1; then
		echo "# rpm -V $THISRPM"
		if rpm -V $THISRPM; then
			echo "Status: Passed"
		else
			echo "Status: WARNING"
		fi
	else
		echo "package $THISRPM is not installed"
		echo "Status: Skipped"
	fi
	echo
}

## Docs  ##
section_header "Referencee Documentation"
echo -e "Current Documentation:
\t https://documentation.suse.com/en-us/sles-sap/15-SP1/
Tuning: 
\t https://documentation.suse.com/sles-sap/12-SP4/single-html/SLES4SAP-guide/#sec-saptune
Best Practice Guides: \t https://documentation.suse.com/sbp/all/
\tSAP HANA SR Performance Optimized Scale up:\t https://documentation.suse.com/sbp/all/pdf/SLES4SAP-hana-sr-guide-PerfOpt-12_color_en.pdf 
\tSAP HANA SR Performance Optimized: Scale out:\t https://documentation.suse.com/sbp/all/pdf/SLES4SAP-hana-scaleOut-PerfOpt-12_color_en.pdf
\tSAP HANA SR Cost Optimized: SLES 12sp1+:\t https://www.suse.com/media/white-paper/sap_hana_sr_cost_optimized_scenario_12_sp1.pdf?_ga=2.126091149.1277468344.1580824358-887832554.1512142213  
\tSAP S/4 HANA - Enqueue Replication High Availability Cluster Guide:\t https://documentation.suse.com/sbp/all/pdf/SAP_S4HA10_SetupGuide-SLE12_color_en.pdf
"
#############################################################
section_header "Supportconfig Plugin for $TITLE, v${SVER}"
RPMLIST="
SAPHanaSR
sapconf
tuned
saptune
sap-suse-cluster-connector
sap_suse_cluster_connector
SAPHanaSR-ScaleOut
"

for THISRPM in $RPMLIST; do
	validate_rpm_if_installed $THISRPM
done

## SAP BASIC Tuning ##
section_header "SAP Tuning information"

RELEASE=$(grep ^VERSION= /etc/os-release)
echo -e  "OS Release: $RELEASE \n"
if [ $RELEASE == 'VERSION="11.4"' ]; then
	plugin_command "chkconfig -l boot.sapconf"
	plugin_command "cat /etc/sysconfig/sapconf | grep -v '^\s*\#\|^$'"
else 
	plugin_command "systemctl status sapconf"
	plugin_command "systemctl status tuned.service"
	plugin_command "tuned-adm active"
	plugin_command "saptune version"
	plugin_command "saptune solution list"
	plugin_command "saptune note list"
	plugin_command "saptune solution verify"
fi 

## SAP Host Agent ##
section_header "SAP Host Agent Information"
plugin_command "/usr/sap/hostctrl/exe/saphostexec -version"
plugin_command "/usr/sap/hostctrl/exe/saphostexec -status"
plugin_command "/usr/bin/cat /usr/sap/sapservices"

## SAP Exit Code Index ##
SAPCONTROLEXIT="sapcontrol return codes: \n 
  0  Last webmethod call successful \n 
  1  Last webmethod call failed, invalid parameter \n 
  2  StartWait, StopWait, WaitforStarted, WaitforStopped, RestartServiceWait timed out \n 
  3  GetProcessList succeeded, all processes running correctly \n 
  4  GetProcessList succeeded, all processes stopped \n"
SAPHDB1="lanscapeHostConfiguration.py return codes: \n 
  0  Fatal \n 
  1  Error \n
  2  Warning \n 
  3  Info \n 
  4  OK \n 
  5  Ignore \n"
SAPHDB2="systemReplicationStatus.py return codes: \n 
  10  NoHSR \n
  11  Error \n 
  12  Unknown ( Normal rc for Secondaray/slave node ) \n 
  13  Initializing \n 
  14  Syncing \n 
  15  Active ( Desired state for Primary/master node ) \n"

# Get SAP Instances using saphostctrl function. Relies on sap interface to be working. 
SAP_CONFIG="sap_config.txt"
/usr/sap/hostctrl/exe/saphostctrl -function ListInstances | awk '{print $4,$6}' &> $SAP_CONFIG

while read LINE
do
	SID=$(echo $LINE | awk '{print $1}')
	SIDADM="$(tr '[:upper:]' '[:lower:]' <<< $SID)adm"
	INST=$(echo $LINE | awk '{print $2}')
	INST_NAME="SID=$SID:InstanceNumber=$INST"
	INSTANCES+=("${INST_NAME} ${SIDADM} ${SID} ${INST}")
done < $SAP_CONFIG
rm -r $SAP_CONFIG

section_header "$TITLE Troubleshooting Commands"
plugin_command "/usr/sap/hostctrl/exe/saphostctrl -function ListInstances"

# Run through each instance detected and display information about it
INST_CNT=1
LABEL=0
ADM=1
SID=2
NUM=3
for INSTANCE in "${INSTANCES[@]}"
do
	# take the INSTANCE variable and turn it into a new array called ELEMENT. Rather than refer to the items in the array by their numeric placement the above 4 variables will be used as reference.
	read -r -a ELEMENT <<< $INSTANCE
	section_header "$TITLE Instance $INST_CNT of ${#INSTANCES[@]}: ${ELEMENT[${LABEL}]}"
	HDBEXIST=true
	plugin_command "su - ${ELEMENT[${ADM}]} -c 'HDB version'"
	if [[ $? == 0 ]]; then
		echo "RETURN CODE: $?"; echo
		plugin_command "SAPHanaSR-monitor"
		echo "RETURN_CODE: $?"; echo 
		plugin_command "SAPHanaSR-showAttr"
		echo "RETURN_CODE: $?"; echo 
		plugin_command "su - ${ELEMENT[${ADM}]} -c 'hdbnsutil -sr_state'"
		echo "RETURN CODE: $?"; echo
		plugin_command "su - ${ELEMENT[${ADM}]} -c 'HDBSettings.sh landscapeHostConfiguration.py --sapcontrol=1'"
		echo "RETURN CODE: $?"; echo -e $SAPHDB1; echo
		plugin_command "su - ${ELEMENT[${ADM}]} -c 'HDBSettings.sh systemReplicationStatus.py'"
		echo "RETURN CODE: $?"; echo -e $SAPHDB2; echo
		plugin_command "su - ${ELEMENT[${ADM}]} -c 'HDBSettings.sh systemOverview.py'"
		echo "RETURN CODE: $?"; echo
		plugin_command "su - ${ELEMENT[${ADM}]} -c 'HDB info'"
		echo "RETURN CODE: $?"; echo
	else
		echo "RETURN CODE: $?"; echo
		HDBEXIST=false
	fi
	plugin_command "su - ${ELEMENT[${ADM}]} -c 'sapcontrol -nr ${ELEMENT[${NUM}]} -function GetSystemInstanceList'"
	plugin_command "su - ${ELEMENT[${ADM}]} -c 'sapcontrol -nr ${ELEMENT[${NUM}]} -function GetProcessList'"
	echo "RETURN CODE: $?"; echo -e $SAPCONTROLEXIT; echo

	INSTANCE_PROFILE_DIR=$(su - ${ELEMENT[${ADM}]} -c 'cdpro && pwd' 2>/dev/null)
	INSTANCE_CONFIG_DIR=$(su - ${ELEMENT[${ADM}]} -c 'cdcoc && pwd' 2>/dev/null)
	
	if [[ -d $INSTANCE_CONFIG_DIR ]] && [[ $HDBEXIST == true ]]; then
		pconf_files ${INSTANCE_CONFIG_DIR}/global.ini ${INSTANCE_CONFIG_DIR}/nameserver.ini
	fi
	if [[ -d $INSTANCE_PROFILE_DIR ]]; then
		pconf_files ${INSTANCE_PROFILE_DIR}/${ELEMENT[${SID}]}_*
	fi
	 INST_CNT=$[ INST_CNT + 1 ]
## Adding support for sap-suse-cluster-connector  ##
        plugin_command "rpm -qa | grep -E 'sap-suse-cluster-connector|sap_suse_cluster_connector'"
        if [ $? -eq 0 ]; then
                plugin_command "su - ${ELEMENT[${ADM}]} -c 'sapcontrol -nr ${ELEMENT[${NUM}]} -function HAGetFailoverConfig'"
                echo "RETURN CODE: $?"; echo 
                plugin_command "su - ${ELEMENT[${ADM}]} -c 'sapcontrol -nr ${ELEMENT[${NUM}]} -function HACheckFailoverConfig'"
                echo "RETURN CODE: $?"; echo 
                plugin_command "su - ${ELEMENT[${ADM}]} -c 'sapcontrol -nr ${ELEMENT[${NUM}]} -function HACheckConfig'"
                echo "RETURN CODE: $?"; echo 
        fi
done
## Adding some basic cluster commands.  Refer to ha.txt in supportconfig for additional ##
section_header "$TITLE Basic Cluster Configuration"
	plugin_command "crm_mon -A -r -1"
	plugin_command "crm configure show"

section_header "$TITLE Log Files"
        plugin_command "grep -E -i 'saphana|SAPDatabase|SAPInstance|SAPStartsrv|sapcontrol|saphostctrl' /var/log/messages | tail -1000"
        if ! [ $RELEASE == 'VERSION="11.4"' ]; then
                plugin_command "grep -E -i 'saphana|SAPDatabase|SAPInstance|SAPStartsrv|sapcontrol|saphostctrl' /var/log/pacemaker.log | tail -1000"
        fi
