#!/usr/bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# bos72V src/bos/usr/sbin/no/restart_inetd 1.2 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2017,2020 
# 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 
# This fine does a best effort attempt to stop inetd and attempts to start the daemon again
# with srcmstr or manual. 
# Returns:
# 0 if it was successful at starting inetd with startsrc.
# 1 if it was successful at starting inetd manually.
# 2 if it failed to start inetd.

export LC_ALL=C
export i_stop_inetd=0
export src_status="unknown"

# Find if srcmstr is running. 
if ps -e -@ Global | grep -w srcmstr 2>&1 >/dev/null; then
	export src_running="TRUE"
else 
	unset src_running
fi

# If SRC is running try to stop inetd a maximum of 10 times.
while [[ ("${src_running}" = "TRUE") && (i_stop_inetd -le 9) && ("${src_status}" != "inoperative") ]]
do
	i_stop_inetd=$i_stop_inetd+1
	stopsrc -s inetd 2>&1 >/dev/null
	src_status=`lssrc -s inetd | grep inetd | awk '{print $3}'`
	sleep 1
done

# Cannot call lssrc if srcmstr is not running. Just leave as unknown.
if [[ "${src_running}" = "TRUE" ]]
then
	src_status=`lssrc -s inetd | grep inetd | awk '{print $3}'`
fi

# If we are not inoperable, kill manually. This will catch cases where src is not running or
# if we could not stopsrc successfully.
if [[ "${src_status}" != "inoperative" ]]
then
	kill -9 `ps -e -F 'uid pid command'  -@ Global | awk '$3 == "inetd" { print $2; }'` 2>&1 >/dev/null
fi

# Now restart inetd, if available try startsrc otherwise do manually.
startsrc_success=1
if [[ "${src_running}" = "TRUE" ]]
then
	startsrc -s inetd 2>&1 >/dev/null
	startsrc_success=$?
fi

if [[ $startsrc_success	-eq 0 ]]
then
	#Success
	exit 0
fi

# Fail or no srcmstr try manual.
echo setopt: startsrc failed[ srcmstr not running? ], errno = $! 1>&2
echo "trying to start 'inetd' directly..." 1>&2
/usr/sbin/inetd 

if [[ $? -eq 0 ]]
then
	#Success on manual start
	echo done 1>&2
	exit 1
fi
echo failed to start 'inetd' 1>&2
# Fail
exit 2
