#!/bin/bash

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

VERSION=1.6.104

### BEGIN INIT INFO
# Provides:          vividcortex
# Required-Start:    $remote_fs $local_fs $syslog
# Required-Stop:     $remote_fs $local_fs $syslog
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 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=""
AGENTS="vc-aggregator vc-mysql-query vc-mysql-metrics vc-os-metrics"


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

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

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

lockfile="/var/lock/subsys/$SERVICE"
RETVAL=0

start() {
	if [ ! -f "$lockfile" ]; then
		echo -n $"Starting $NAME: "	
	    daemon "$DAEMON $SUPERVISOR_ARGS"
	    RETVAL=$?
	    [ $RETVAL -eq 0 ] && touch "$lockfile"
	    echo
	fi
	return $RETVAL
}

stop() {
	# Return
	#   0 if daemon has been stopped
	#   7 if daemon was already 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.)
	echo -n "Stopping $NAME: "
	killproc "$DAEMON"
	RETVAL=$?
	[ "$RETVAL" -ne 0 -a "$RETVAL" -ne 7 ] && return "$RETVAL"
	rm -f "$lockfile" /var/run/vc-agent-007.pid

	# Can't use killproc() for individual agents: it will emit failure
	# messages when attempting to stop any that are not currently running.
	PIDLIST=()
	for a in $AGENTS; do
		pids=`pidofproc "${BIN_PATH}/${a}"`
		# pidofproc() can return more than one PID.
		for pid in "${pids}"; do
			PIDLIST+=(${pid})
		done
	done

	if [ "${#PIDLIST[@]}" -gt 0 ]; then
		# Kill all child agents in one fell swoop.
		kill -TERM "${PIDLIST[@]}" > /dev/null 2>&1

		# Wait a short bit to allow agents to exit politely...
		sleep 2
		# ...and then keep retrying for 5 seconds with -KILL if they won't.
		count=0
		TOKILL=$(ps -o pid= ${PIDLIST[@]})
		while [ -n "${TOKILL}" -a "${count}" -lt 5 ]; do
			kill -KILL "${TOKILL}" > /dev/null 2>&1
			sleep 1
			TOKILL=$(ps -o pid= ${PIDLIST[@]})
			count=$((count + 1))
		done
	fi
	rm -f /var/lock/${a}_*.lock /var/run/${a}_*.pid

	echo
	return 0
}

restart() {
	stop
	start
}	

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
restart)
	restart
	;;
status)
	status "$NAME"
	RETVAL=$?
	;;
*)
	echo $"Usage: $0 {start|stop|restart|status}"
	RETVAL=2
esac

exit $RETVAL
