#! /bin/sh
### BEGIN INIT INFO
# Provides:          besrelay
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts BigFix Relay
# Description:       Performs all necessary functions to operate the BigFix Relay
# Depends:           besclient
### END INIT INFO

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="BigFix Relay"
NAME=BESRelay
DAEMON=/opt/BESRelay/bin/$NAME
DAEMON_ARGS=""
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/besrelay

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# The "start_skipclientrestart" option is not known by systemctl, so the relay process is started, but not the service.
# The workaround is using a temporary file and resetting the option to "start"; the file is deleted when the script
# is called by the systemctl redirection.
[ "X$1" = "Xstart_skipclientrestart" ] && touch /tmp/$NAME.SKIP_CLIENT_RESTART && set -- "start"

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#import the system locale information
[ -r /etc/default/locale ] && . /etc/default/locale
[ -n "$LANG" ] && export LANG


#
# Function that starts the daemon/service
#
do_start()
{
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started

	SKIP_CLIENT_RESTART="noskip"
	[ -f /tmp/$NAME.SKIP_CLIENT_RESTART ] && SKIP_CLIENT_RESTART="skipclientrestart" && rm -f /tmp/$NAME.SKIP_CLIENT_RESTART 2>/dev/null

	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
        elif [ -f /usr/bin/perl ]; then
                GATHERURL_CONFIG=$( /usr/bin/perl -ne 'if( m#^__Installer_Masthead_GatherURL\s+=\s+(http://\S+)# ) { print $1; }' $relayConfigPath)
        fi

        CLIENT_RESTART_NEEDED=0
        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 [ -n $GATHERURL_MASTHEAD ] && [ "x$GATHERURL_MASTHEAD" != "x$GATHERURL_CONFIG" ]; then
                        cat $relayConfigPath.default > $relayConfigPath
                        setup_configfile $BESClientActionMastheadPath $relayConfigPath $GATHERURL_MASTHEAD

                        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

        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
                || return 1
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
                $DAEMON_ARGS \
                || return 2

        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
                        ( export BES_LIBPATH=/opt/BESClient/bin; $CLIENT_INIT restart )
                fi
        fi

}

#
# Function that stops the daemon/service
#
do_stop()
{
	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred
	start-stop-daemon --stop --quiet --retry=TERM/120/KILL/5 --name $NAME --ppid=1 2>/dev/null
	RETVAL="$?"
	if [ "$RETVAL" -ge 3 ]; then
		start-stop-daemon --stop --quiet --retry=TERM/120/KILL/5 --name $NAME
		RETVAL="$?"
	fi
	[ "$RETVAL" = 2 ] && return 2
	# Wait for children to finish too if this is a daemon that forks
	# and if the daemon is only ever run from this initscript.
	# If the above conditions are not satisfied then add some other code
	# that waits for the process to drop all resources that could be
	# needed by services started subsequently.  A last resort is to
	# sleep for some time.
	start-stop-daemon --stop --quiet --oknodo --retry=TERM/120/KILL/5 --exec $DAEMON --ppid=1 2>/dev/null
	RETVAL2="$?"
	if [ "$RETVAL2" -ge 3 ]; then
		start-stop-daemon --stop --quiet --oknodo --retry=TERM/120/KILL/5 --exec $DAEMON
		RETVAL2="$?"
	fi
	[ "$RETVAL2" = 2 ] && return 2
	# Many daemons don't delete their pidfiles when they exit.
	rm -f $PIDFILE
	return "$RETVAL"
}

setup_configfile() {
	masthead=$1
	configfile=$2
	gatherurl=$3

	echo >> $configfile

	echo "[Software\\BigFix\\Enterprise Server]" >> $configfile
	printf "__Installer_Masthead_GatherURL\t\t= %s\n\n" "$gatherurl" >> $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
		printf "value\t\t= %s\n\n" "$URL" >> $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" -a -n "$PORT" ]; then
		echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_BESRelay_PostResults_ParentRelayURL]" >> $configfile
		printf "value\t\t= %s\n\n" "$URL" >> $configfile
		echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_BESRelay_HTTPServer_PortNumber]" >> $configfile
		printf "value\t\t= %s\n\n" "$PORT" >> $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
		printf "HttpContentLocation\t\t= %s/bfmirror/bfsites\n\n" "$URL" >> $configfile

		echo "[Software\\BigFix\\EnterpriseClient\\Settings\\Client\\_Enterprise Server_ClientRegister_UDPMessagePort]" >> $configfile
		printf "value\t\t= %s\n\n" "$PORT" >> $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
		printf "value\t\t= %s\n\n" "$URL" >> $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
		printf "DownloadMirror URL\t\t= %s\n\n" "$URL" >> $configfile
	fi
}

case "$1" in
  start)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
	do_start
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  start_skipclientrestart)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
	do_start "skipclientrestart"
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  stop)
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
	do_stop
	case "$?" in
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
	esac
	;;
  restart|force-reload)
	#
	# If the "reload" option is implemented then remove the
	# 'force-reload' alias
	#
	log_daemon_msg "Restarting $DESC" "$NAME"
	do_stop
	case "$?" in
	  0|1)
		do_start
		case "$?" in
			0) log_end_msg 0 ;;
			1) log_end_msg 1 ;; # Old process is still running
			*) log_end_msg 1 ;; # Failed to start
		esac
		;;
	  *)
	  	# Failed to stop
		log_end_msg 1
		;;
	esac
	;;
  *)
	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac

:
