#!/bin/sh

if [ "" == "$MEDIACASTER_DIR" ]; then
    echo "This script must be called from daemon wrapper.  Exiting."
    exit 1
fi

HOST_PIDFILE=/tmp/kwilt-command.pid

#-----------#
# Functions #
#-----------#

# Start the kwilt-command daemon
kwilt_command_start () {
	kwilt_command_status > /dev/null
	STATUS=$?
	if [ "$STATUS" == "0" ]; then
		echo "kwilt-command daemon is already running."
		return 1
	elif [ "$STATUS" == "2" ]; then
		echo "kwilt-command daemon is stopping or dead."
		return 1
	fi

	echo -n "Starting kwilt-command daemon: "

	# Prioritize loading guest dynamic libraries over the host ones
    LD_LIBRARY_PATH=${MEDIACASTER_DIR}/usr/lib:${MEDIACASTER_DIR}/lib
    export LD_LIBRARY_PATH
    ${MEDIACASTER_DIR}/lib/ld-uClibc.so.0 "${MEDIACASTER_DIR}/sbin/host/kwilt-command" --pidfile "${HOST_PIDFILE}" -V7 -d
	unset LD_LIBRARY_PATH
	
	echo "OK"
	return 0
}

# Query the kwilt-command daemon status
kwilt_command_status () {
	if [ ! -f "$HOST_PIDFILE" ]; then
		echo "kwilt-command daemon is stopped."
		return 1
	fi

	KWILT_COMMAND_PID=`cat ${HOST_PIDFILE}`

	# Verify kwilt-command hasn't crashed
	if ! kill -0 ${KWILT_COMMAND_PID}; then
		echo "kwilt-command daemon is stopped, but PID file exists: PID [${KWILT_COMMAND_PID}] : $HOST_PIDFILE"
		return 2
	fi

	echo "kwilt-command daemon is running."
	return 0
}

# Stop the MediaCaster daemon
kwilt_command_stop () {
	kwilt_command_status > /dev/null
	STATUS=$?
	if [ "$STATUS" != "0" ]; then
		echo "kwilt-command daemon is not running."
		return 1
	fi

	# Kill the main daemon loop
	echo "Stopping kwilt-command daemon:"
	local KWILT_COMMAND_PID=`cat ${HOST_PIDFILE}`

	if ! kill -TERM ${KWILT_COMMAND_PID}; then
		echo "Failed"
		return 1
	fi

	echo "OK"
	return 0
}

#------------------#
# Command Dispatch #
#------------------#

case "$1" in
	start)
		kwilt_command_start
		;;
	status)
		kwilt_command_status
		;;
	stop)
		kwilt_command_stop
		;;
    restart)
    	kwilt_command_stop
    	kwilt_command_start
    	;;
	*)
		echo "USAGE: kwilt-command {start|stop|restart|status}"
		exit 1
		;;
esac

exit $?
