#!/bin/sh

# This program is Copyright (c) 2013-2018 VividCortex, Inc. All rights reserved.

VERSION=unknown

### BEGIN INIT INFO
# Provides:          vividcortex
# Required-Start:    $remote_fs $local_fs
# Required-Stop:     $remote_fs $local_fs
# Should-Start:      $syslog $network $named $time
# Should-Stop:       $syslog $network $named $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: VividCortex supervisor daemons
# Description:       agent_007 is the main VividCortex daemon. It's in charge
#                    of starting other agents as required and updating
#                    binaries when new versions are available.
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin

DESC="VividCortex supervisor daemon"
NAME=vc-agent-007
SERVICE=vividcortex
BIN_PATH=/usr/local/bin
DAEMON=$BIN_PATH/$NAME
SUPERVISOR_ARGS="-startup-network-retries=10 -startup-network-retry-interval=10s"
AGENTS="vc-aggregator vc-cstar-query vc-cstar-metrics vc-es-query vc-es-metrics vc-mongo-query vc-mongo-metrics vc-mysql-query vc-mysql-metrics vc-os-metrics vc-pgsql-query vc-pgsql-metrics vc-redis-query vc-redis-metrics"
set_conf_file=0
if [ "${set_conf_file}" != "0" ]; then
	SUPERVISOR_ARGS="${SUPERVISOR_ARGS} -config-file=/etc/vividcortex/global.conf"
fi

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

# Read optional config file
[ -r /etc/default/$SERVICE ] && . /etc/default/$SERVICE

# For old distros: tiny implementations, to be replaced by LSB functions
log_daemon_msg() {
	test -z "${2:-}" && echo -n "$1:" || echo -n "$1: $2"
}
log_end_msg() {
	test $1 -eq 0 && echo "." || echo " failed!"
	return $1
}
status_of_proc() {
	local status
	status="0"
	pidofproc $1 >/dev/null || status="$?"
	if [ "$status" = "0" ]; then
		echo "$2 is running"
	elif [ "$status" = "4" ]; then
		echo "could not access PID file for $2"
	else
		echo "$2 is not running"
	fi
	return $status
}

# Load required variables and functions (LSB)
[ -r /lib/init/vars.sh ] && . /lib/init/vars.sh
. /lib/lsb/init-functions

# Set HOME in case it isn't (boot) or points to a user dir (sudo)
HOME=~root
test -d "${HOME}" || HOME=/root
test -d "${HOME}" || HOME=
export HOME

# Are we dealing with an ancient start-stop-daemon?
start-stop-daemon --help | grep -q retry && SSD_LEGACY=0 || SSD_LEGACY=1

do_start() {
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	start-stop-daemon --start --quiet --exec $DAEMON --test > /dev/null || return 1
	start-stop-daemon --start --quiet --exec $DAEMON -- $SUPERVISOR_ARGS || return 2
}

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

	# Kill vc-agent-007, return if that cannot be done. (If it wasn't running, that's OK.)
	# (Trying to kill the other agents if vc-agent-007 won't die will only lead to madness.)
    if [ ${SSD_LEGACY} -eq 0 ]; then
		start-stop-daemon --stop --quiet --oknodo --retry=TERM/5/KILL/5 --exec ${DAEMON} --user root
		RETVAL="$?"
    else
		start-stop-daemon --stop --quiet --oknodo --name ${NAME} --pidfile=/var/run/${NAME}.pid --user root
		RETVAL="$?"
    fi
	[ "$RETVAL" -ne 0 ] && return "$RETVAL"
	echo -n "${NAME}" | grep -q '^vc-[0-9A-Za-z-]\+$' && rm -f "/var/lock/${NAME}"* "/var/run/${NAME}"* "/var/lock/vividcortex/${NAME}"* "/var/run/vividcortex/${NAME}"*

	FAILVAL=0
	for a in $AGENTS; do
		if [ -x "${BIN_PATH}/${a}" ]; then
			if [ ${SSD_LEGACY} -eq 0 ]; then
				start-stop-daemon --stop --quiet --oknodo --retry=TERM/5/KILL/5 --exec "${BIN_PATH}/${a}" --user root
				RETVAL=$?
			else
				# It's too dangerous to kill w/o full path or pidfile; assume supervisor succeeded
				RETVAL=0
			fi
			if [ "$RETVAL" -eq 0 ]; then
				if echo -n "${a}" | grep -q '^vc-[0-9A-Za-z-]\+$'; then
					rm -rf "/var/run/vividcortex/${a}"*
					rm -f "/var/lock/${a}"* "/var/run/${a}"* "/var/lock/vividcortex/${a}"* "/var/run/vividcortex/${a}"*
				fi
			else
				FAILVAL="$RETVAL"
			fi
		else
			# Just in case there's something old left behind.
			if echo -n "${a}" | grep -q '^vc-[0-9A-Za-z-]\+$'; then
				rm -rf "/var/run/vividcortex/${a}"*
				rm -f "/var/lock/${a}"* "/var/run/${a}"* "/var/lock/vividcortex/${a}"* "/var/run/vividcortex/${a}"*
			fi
		fi
	done

	# Will return 0 only if all agents were killed successfully.
	return $FAILVAL
}

case "$1" in
	start)
		pidofproc "$DAEMON" >/dev/null && exit 0
		[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
		do_start
		case "$?" in
			0|1)
				[ "$VERBOSE" != no ] && log_end_msg 0
				exit 0
				;;
			*)  [ "$VERBOSE" != no ] && log_end_msg 1
				exit 1
				;;
		esac
		;;

	stop)
		[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
		do_stop
		case "$?" in
			0|1)
				[ "$VERBOSE" != no ] && log_end_msg 0
				exit 0
				;;
			*)
				[ "$VERBOSE" != no ] && log_end_msg 1
				exit 1
				;;
		esac
		;;

	status)
		status_of_proc "$DAEMON" "$NAME"
		exit $?
		;;

	restart|force-reload)
		log_daemon_msg "Restarting $DESC" "$NAME"
		do_stop
		case "$?" in
			0|1)
				do_start
				case "$?" in
					0)
						log_end_msg 0
						exit 0
						;;
					*)
						log_end_msg 1 # 1 old process is still running, other: failed to start
						exit 1
						;;
				esac
				;;
			*)
				log_end_msg 1 # Failed to stop
				exit 1
				;;
		esac
		;;

	reload)
		exit 3
		;;

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

exit 1 # should not reach here; 1 = generic or unspecified error
