#!/bin/sh
# Recovery Handler start-up script.

APP_NAME="reset-handler"
APP_BIN="/usr/bin/${APP_NAME}"
APP_OPTS=""
APP_PID_FILE="/var/run/${APP_NAME}.pid"

WD_NAME="barix_watchdog"
WD_BIN="/usr/bin/${WD_NAME}"

check_wd() {
    # Argument $1 is a process full command line regular expression to be used
    # with pgrep/pkill.
	proc_re=$1
    # Argument $2 is the timeout in seconds to wait for a process still running
    # before killing it.
	timeout=$2

	# Loop waiting for process to exit, with timeout.
	ended=0
	count=1
	echo "Waiting for '${proc_re}' to end..."
	while [ ${count} -le ${timeout} ]; do
		if pgrep -f "${proc_re}" > /dev/null; then
			echo "Still running..."
			sleep 1
		else
			echo "Waiting for '${proc_re}' to end...DONE"
			ended=1
			break
		fi
		((count++))
	done

	# Force process killing if waiting timed out.
	if [ ${ended} -ne 1 ]; then
		echo "Waiting for '${proc_re}' to end...FAILED => Kill it!"
		pkill -9 -f "${proc_re}"
		rc=$?
		echo "Killed '${proc_re}' (rc=${rc})"
	fi
}

start_wd() {
	echo "Starting '${APP_NAME}' via '${WD_NAME}'..."
	start-stop-daemon -S -b -o -x ${WD_BIN} -p ${APP_PID_FILE} -m -- \
		${APP_BIN} ${APP_OPTS}
	rc=$?
	if [ ${rc} -ne 0 ]; then
		echo "Starting '${APP_NAME}' via '${WD_NAME}'...FAILED (rc=${rc})"
		# Should not have been created, but just in case.
		rm -f ${APP_PID_FILE}
		exit ${rc}
	fi
	echo "Starting '${APP_NAME}' via '${WD_NAME}'...OK"
}

stop_wd() {
	echo "Stopping '${APP_NAME}' via '${WD_NAME}'..."
	# Give a chance for the wd/app to stop cleanly with SIGINT.
	start-stop-daemon -K -s 2 -o -p ${APP_PID_FILE}
	rc=$?
	echo "Stopping '${APP_NAME}' via '${WD_NAME}'...DONE (rc=${rc})"
	# Make sure the wd/app are stopped, forcing if necessary.
	check_wd "${WD_BIN} ${APP_BIN}" 5
	check_wd "${APP_BIN}" 5
	# Drop the PID file.
	rm -f ${APP_PID_FILE}
}

start() {
	# Just defer to start_wd().
	echo "${APP_NAME}: Starting the ${APP_NAME} application..."
	start_wd
	echo "${APP_NAME}: Starting the ${APP_NAME} application...DONE"
}

stop() {
	# Just defer to stop_wd().
	echo "${APP_NAME}: Stopping the ${APP_NAME} application..."
	stop_wd
	echo "${APP_NAME}: Stopping the ${APP_NAME} application...DONE"
}

restart() {
	stop
	start
}


case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		restart
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
esac

exit 0
