#!/bin/sh -
#
# chkconfig:   345 99 01
# description: Starts and stops the OpenNMS Sentinel distributed client
# processname: java
#
### BEGIN INIT INFO
# Provides:          sentinel
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: OpenNMS Sentinel
# Description:       Horizontal Scaling for OpenNMS Subsystems
### END INIT INFO

ME="$0"

NAME="sentinel"
DESC="Sentinel"
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
SENTINEL_HOME="/usr/share/sentinel"
SYSCONFDIR="/etc/default"
RUNAS=sentinel
STOP_RETRIES=10
STOP_WAIT=5

export NAME DESC PATH

if [ -f /lib/lsb/init-functions ]; then
	# shellcheck disable=SC1090,SC1091
	. /lib/lsb/init-functions
fi

if [ -f /etc/rc.d/init.d/functions ]; then
	# shellcheck disable=SC1090,SC1091
	. /etc/rc.d/init.d/functions
fi

if [ -z "$JAVA_HOME" ]; then
	JAVA_HOME="$("${SENTINEL_HOME}/bin/find-java.sh" 1.8.0 1.8.9999)"
fi

if [ -r "${SYSCONFDIR}/sentinel" ]; then
	# shellcheck disable=SC1090,SC1091
	. "${SYSCONFDIR}/sentinel"
fi

if [ -r "${SENTINEL_HOME}/sentinel.conf" ]; then
	# shellcheck disable=SC1090,SC1091
	. "${SENTINEL_HOME}/sentinel.conf"
fi

if [ -r "${SENTINEL_HOME}/etc/sentinel.conf" ]; then
	# shellcheck disable=SC1090,SC1091
	. "${SENTINEL_HOME}/etc/sentinel.conf"
fi

# The user config can set JAVA_OPTS, but Karaf will not
# do ANY of its own JAVA_OPTS processing if it is already
# set, so work around this by grabbing DEFAULT_JAVA_OPTS
# now, rather than letting Karaf init do it.

# shellcheck disable=SC1090,SC1091
. "${SENTINEL_HOME}/bin/inc"
setupDefaults

# always dump heap if we OOM
DEFAULT_JAVA_OPTS="${DEFAULT_JAVA_OPTS} -XX:+HeapDumpOnOutOfMemoryError"

# combine user JAVA_OPTS with the defaults from Karaf
JAVA_OPTS="${DEFAULT_JAVA_OPTS} ${JAVA_OPTS}"

# export any default configurable variables from sysconf
export JAVA_HOME JAVA_MIN_MEM JAVA_MAX_MEM MAX_FD JAVA JAVA_DEBUG_OPTS JAVA_DEBUG_PORT JAVA_OPTS CLASSPATH KARAF_DEBUG LD_LIBRARY_PATH

run_as() {
	if [ "$(id -n -u)" "!=" "${RUNAS}" ]; then
		DAEMON="$(daemon --user="${RUNAS}" true >/dev/null 2>&1 && echo daemon)"
		RUNUSER="$(runuser -u "${RUNAS}" true 2>/dev/null && which runuser 2>/dev/null)"
		if [ -n "${DAEMON}" ]; then
			"$DAEMON" --user="${RUNAS}" "$@" >/dev/null 2>&1
		elif [ -n "${RUNUSER}" ] && [ -x "${RUNUSER}" ]; then
			exec "${RUNUSER}" -u "${RUNAS}" "$@"
		else
			exec /usr/bin/sudo -u "${RUNAS}" "$@"
		fi
	else
		exec "$@"
	fi
}

get_root_pid() {
	ROOT_INSTANCE_PID=0
	if [ -f "${SENTINEL_HOME}/instances/instance.properties" ];
	then
		ROOT_INSTANCE_PID=$(sed -n -e '/item.0.pid/ s/.*\= *//p' "${SENTINEL_HOME}/instances/instance.properties")
	fi
	echo "$ROOT_INSTANCE_PID"
}

is_running() {
  PID=$(get_root_pid)
  if [ "${PID}" -ne "0" ] && ps p "$PID" > /dev/null; then
    return 0
  else
    return 1
  fi
}

stop_sentinel() {
	run_as "$SENTINEL_HOME"/bin/stop >/dev/null
}

kill_sentinel() {
	SIGNAL="$1"
	if [ -z "$SIGNAL" ]; then
		SIGNAL="-15"
	fi
	PID=$(get_root_pid)
	if [ "$PID" -gt 0 ]; then
		kill $SIGNAL "$PID"
	fi
}


COMMAND="$1"

case "$COMMAND" in

	start)
		if is_running; then
			echo "$DESC is running."
			exit 0
		fi

		"${SENTINEL_HOME}/bin/ensure-user-ping.sh" "${RUNAS}" || :
		if [ ! -d "${SENTINEL_HOME}/data/tmp" ]; then
			install -d -m 755 -o "${RUNAS}" "${SENTINEL_HOME}/data/tmp"
		fi
		run_as "$SENTINEL_HOME"/bin/start
		exit $?
		;;

	stop)
		if is_running; then
			printf "Stopping %s: " "$DESC"
			STOP_ATTEMPTS=0
			while [ $STOP_ATTEMPTS -lt $STOP_RETRIES ]; do
				stop_sentinel
				if is_running; then
					STOP_ATTEMPTS="$((STOP_ATTEMPTS + 1))"
					sleep $STOP_WAIT
				else
					echo "OK"
					exit 0
				fi
			done
			echo "FAILED"

			printf "Killing %s: " "$DESC"
			kill_sentinel
			if is_running; then
				echo "FAILED"
			else
				echo "OK"
				exit 0
			fi

			printf "Force-killing %s: " "$DESC"
			kill_sentinel -9
			if is_running; then
				echo "FAILED"
				exit 1
			fi
			echo "OK"
			exit 0
		else
			echo "$DESC is not running."
			exit 0 # LSB specifies calling "stop" on a stopped service is still a success
		fi
		;;

	restart)
		$0 stop >/dev/null 2>&1
		sleep 2
		$0 start
		exit $?
		;;

	try-restart)
		if is_running; then
			echo "$DESC is not running."
			exit 0
		else
			$0 restart
			exit $?
		fi
		;;


	force-reload)
		$0 try-restart
		exit $?
		;;

	status)
		run_as "$SENTINEL_HOME"/bin/status >/dev/null
		RETVAL="$?"
		if [ $RETVAL -eq 0 ]; then
			echo "$DESC is running."
			exit 0
		else
			echo "$DESC is stopped."
			exit 3
		fi
		;;

	*)
		echo "Usage: $0 {start|stop|restart|try-restart|force-reload|status}" >&2
		exit 1
		;;
esac
