#!/bin/sh
#
# besrelay:    Starts the BigFix Relay
#
# chkconfig: 2345 99 99
# description: Starts and stops the BigFix Relay daemon
# processname: BESRelay

export SYSTEMCTL_SKIP_REDIRECT=1

# Source function library.
. /etc/init.d/functions

prog=BESRelay
service=besrelay

test -x /opt/BESRelay/bin/$prog || exit 0

start() {
	SKIP_CLIENT_RESTART="${SKIP_CLIENT_RESTART:-noskip$1}"

	echo -n $"Starting BigFix: $prog: "
	
	# For systemd services the system locale is set by systemd.
	# For legacy SysV services, we get it from /etc/locale.conf
	hasSystemd=0
	if [ -e /etc/systemd ] && [ -f /etc/os-release ]; then
		. /etc/os-release
		if [ -n "$VERSION_ID" ]; then
			ver=$(echo $VERSION_ID | sed 's/\..*$//' | sed 's/,.*$//')
			if [ -n "$ver" ] && [ -n "$ID" ]; then
				# rhel >= 7 with systemd. Containers don't support systemd
				[ "$ID" = "rhel" ] && [ "$ver" -ge 7 ] && systemdPid=`pidof systemd` && [ -n "$systemdPid" ] && hasSystemd=1
				# centos >= 7 with systemd
				[ "$ID" = "centos" ] && [ "$ver" -ge 7 ] && hasSystemd=1
				# amazon linux >= 2 with systemd
				[ "$ID" = "amzn" ] && [ "$ver" -ge 2 ] && hasSystemd=1
			fi
		fi
	fi
	if [ "$hasSystemd" -eq 0 ] && [ -f /etc/locale.conf ]; then
		. /etc/locale.conf
		export LANG LC_ALL LC_CTYPE LC_MESSAGES
	fi

	export BESClientActionMastheadPath=/etc/opt/BESClient/actionsite.afxm
	export BES_LIBPATH=/opt/BESRelay/bin

	clientConfigPath=/var/opt/BESClient/besclient.config
	if [ ! -f $clientConfigPath ]; then
		if [ ! -f $clientConfigPath.default ]; then
			failure "Missing config file $clientConfigPath."
			echo
			return 1
		fi
	fi

	GATHERURL_CONFIG=""
	relayConfigPath=/var/opt/BESRelay/besrelay.config
	if [ ! -f $relayConfigPath ]; then
		if [ ! -f $relayConfigPath.default ]; then
			failure "Missing config file $relayConfigPath."
			echo
			return 1
		fi
	else
		if [ -f /usr/bin/perl ]; then
			GATHERURL_CONFIG=$( /usr/bin/perl -ne 'if( m#^__Installer_Masthead_GatherURL\s+=\s+(http://\S+)# ) { print $1; }' $relayConfigPath)
		fi
	fi

	CLIENT_RESTART_NEEDED=0
	if [[ $SKIP_CLIENT_RESTART == "noskip" ]]; then
		if [ -f /usr/bin/perl ]; then
			GATHERURL_MASTHEAD=$( /usr/bin/perl -ne 'if( m#^X-Fixlet-Site-Gather-URL:\s+(http://\S+)# ) { print $1; }' $BESClientActionMastheadPath )

			if [ "x$GATHERURL_MASTHEAD" != "x$GATHERURL_CONFIG" ]; then
				cat $relayConfigPath.default > $relayConfigPath
				setup_configfile $BESClientActionMastheadPath $relayConfigPath $GATHERURL_MASTHEAD

				CLIENT_RESTART_NEEDED=1
			fi
		else
			CLIENT_RESTART_NEEDED=1
		fi
	fi

	stackSizeHardLimitKB=$(ulimit -Hs)
	if [ "$stackSizeHardLimitKB" != "unlimited" ] && [ $stackSizeHardLimitKB -lt 10240 ]; then
		failure "Stack size hard limit ( ulimit -Hs ) too low = $stackSizeHardLimitKB."
		/bin/echo
		return 1
	fi

	stackSizeSoftLimitKB=$(ulimit -Ss)
	if [ "$stackSizeSoftLimitKB" = "unlimited" ] || [ $stackSizeSoftLimitKB -lt 10240 ]; then
		ulimit -Ss 10240
	fi

	daemon /opt/BESRelay/bin/$prog 2> /dev/null
	ret=$?
	[ $ret -eq 0 ] && touch /var/lock/subsys/$service
	echo

	if [[ $CLIENT_RESTART_NEEDED -eq 1 && $SKIP_CLIENT_RESTART == "noskip" ]]; then
		# Backwards compatibility: detect name of installed client init script
		CLIENT_INIT=/etc/init.d/besclient
		if [ ! -f $CLIENT_INIT ]; then
			CLIENT_INIT=`ls -d /etc/init.d/BESClient* | head -1`
		fi

		if [ -f $CLIENT_INIT ]; then
			( export BES_LIBPATH=/opt/BESClient/bin; $CLIENT_INIT restart )
		fi

	fi

	return $ret
}

stop() {
	/bin/echo -n $"Stopping BigFix: $prog: "
	# Find pid.
	pid=`pidof /opt/BESRelay/bin/$prog`
	if [ -z "$pid" ]; then
		ret=1
		RC=0
	else    
		delay=120 
		/bin/kill -TERM $pid >/dev/null 2<&1
		ret=$? 
		sleep 0.2
		count=0
		while checkpid $pid && [ "$count" -lt "$delay" ];
		do sleep 5; count=$(($count+5));
		done 
		if [ "$count" -ge "$delay" ]; then 
			kill -KILL $pid >/dev/null 2<&1
			ret=$?
		fi
		sleep 0.2
		checkpid $pid
		RC=$?
	fi
	[ "$RC" -eq 0 ] && failure $"BESRelay shutdown" || success $"BESRelay shutdown"
		RC=$((! $RC))
	[ $ret -eq 0 ] && rm -f /var/lock/subsys/$service
	/bin/echo
	return $ret
}

restart() {
	stop
	start
}

reload() {
	restart
}

status_BESRelay() {
	status /opt/BESRelay/bin/$prog
}

setup_configfile() {
	if [ -f /usr/bin/perl ]; then
		masthead=$1
		configfile=$2
		gatherurl=$3

		echo >> $configfile

		echo "[Software\\BigFix\\Enterprise Server]" >> $configfile
		echo -e "__Installer_Masthead_GatherURL\t\t= $gatherurl\n" >> $configfile

		URL=$( /usr/bin/perl -ne 'if( m#^X-Fixlet-Site-Registration-URL:\s+([[:print:]]+)# ) { print $1; }' $masthead )
		if [ -n "$URL" ]; then
			echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_Enterprise Server_ClientRegister_ParentRelayURL]" >> $configfile
			echo -e "value\t\t= $URL\n" >> $configfile
		fi

		URL=$( /usr/bin/perl -ne 'if( m#^X-Fixlet-Site-Report-URL:\s+([[:print:]]+)# ) { print $1; }' $masthead )
		PORT=$( /usr/bin/perl -ne 'if( m#^X-Fixlet-Site-Report-URL:\s+http://\S+:(\d+)# ) { print $1; }' $masthead )
		if [ -n "$URL" ]; then
			echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_BESRelay_PostResults_ParentRelayURL]" >> $configfile
			echo -e "value\t\t= $URL\n" >> $configfile
			echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_BESRelay_HTTPServer_PortNumber]" >> $configfile
			echo -e "value\t\t= $PORT\n" >> $configfile
		fi

		URL=$(  /usr/bin/perl -ne 'if( m#^X-Fixlet-Site-Gather-URL:\s+(http://\S+:\d+)# ) { print $1; }' $masthead )
		PORT=$( /usr/bin/perl -ne 'if( m#^X-Fixlet-Site-Gather-URL:\s+http://\S+:(\d+)# ) { print $1; }' $masthead )
		if [ -n "$URL" -a -n "$PORT" ]; then
			echo "[Software\\BigFix\\Enterprise Server\\GatherService]" >> $configfile
			echo -e "HttpContentLocation\t\t= $URL/bfmirror/bfsites\n" >> $configfile

			echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_Enterprise Server_ClientRegister_UDPMessagePort]" >> $configfile
			echo -e "value\t\t= $PORT\n" >> $configfile
		fi

		URL=$( /usr/bin/perl -ne 'if( m#^X-BES-Mirror-Gather-URL:\s+([[:print:]]+)# ) { print $1; }' $masthead )
		if [ -n "$URL" ]; then
			echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_BESGather_Comm_ParentRelayURL]" >> $configfile
			echo -e "value\t\t= $URL\n" >> $configfile
		fi

		URL=$( /usr/bin/perl -ne 'if( m#^X-BES-Mirror-Download-URL:\s+([[:print:]]+)# ) { print $1; }' $masthead )
		if [ -n "$URL" ]; then
			echo "[Software\\BigFix\\Enterprise Server\\GatherService]" >> $configfile
			echo -e "DownloadMirror URL\t\t= $URL\n" >> $configfile
		fi
	fi
}

case "$1" in
	start)
		start
		;;
	start_skipclientrestart)
		start "skipclientrestart"
		;;
	stop)
		stop
		;;
	condrestart)
		if [ -f /var/lock/subsys/$service ]; then
			restart
		fi
		;;
	reload|restart)
		restart
		;;
	status)
		status_BESRelay
		;;
	*)
		echo $"Usage: besrelay {start|stop|status|restart|reload|condrestart}"
		exit 1
esac

exit $?
