#!/bin/sh

DAEMON_WATCHDOG_HOST=0
DAEMON_WATCHDOG_GUEST=1

# Check if all required Mediacaster daemons are running and restart any that died.
daemon_watchdog_run() {
	daemon_watchdog_check_process ${DAEMON_WATCHDOG_GUEST} lighttpd      /var/run/lighttpd.pid  /etc/init.d/S50lighttpd
	daemon_watchdog_check_process ${DAEMON_WATCHDOG_HOST}  kwilt-command /tmp/kwilt-command.pid /sbin/host/init.d/kwilt-command
}

# Call a GUEST or HOST start script
daemon_watchdog_start_process () {
	local ENVIRON="$1"
	local INIT_SCRIPT="$2"
	if [ "$ENVIRON" == "$DAEMON_WATCHDOG_GUEST" ]; then
		chroot ${MEDIACASTER_DIR} ${INIT_SCRIPT} start
	else
		"${MEDIACASTER_DIR}${INIT_SCRIPT}" start
	fi
	return $?
}

# Call a GUEST or HOST stop script
daemon_watchdog_stop_process () {
	local ENVIRON="$1"
	local INIT_SCRIPT="$2"
	if [ "$ENVIRON" == "$DAEMON_WATCHDOG_GUEST" ]; then
		chroot ${MEDIACASTER_DIR} ${INIT_SCRIPT} stop
	else
		"${MEDIACASTER_DIR}${INIT_SCRIPT}" stop
	fi
	return $?
}

# Check if a process is alive, and if not, restart it
daemon_watchdog_check_process() {
	local ENVIRON="$1"
	local NAME="$2"
	local PIDFILE="$3"
	local START_SCRIPT="$4"
	local KILL

	if [ "1" == "$isBuildroot" ] && [ "$DAEMON_WATCHDOG_GUEST" == "$ENVIRON" ]; then
		HOST_PIDFILE="${MEDIACASTER_DIR}${PIDFILE}"
	else
		HOST_PIDFILE="${PIDFILE}"
	fi

	if [ "1" == "$isBuildroot" ]; then
		KILL="kill"
	else
		KILL="sudo kill"
	fi

	# Check if the PID file exists
	if [ ! -f ${HOST_PIDFILE} ]; then
		daemon_log_info "PID file $HOST_PIDFILE not found"
		daemon_watchdog_start_process "${ENVIRON}" "${START_SCRIPT}"
		return
	fi

	# Check if the PID file has content
	PID=`cat ${HOST_PIDFILE}`
	if [ "$PID" == "" ]; then
		daemon_log_info "PID file $HOST_PIDFILE was empty"
		rm -f ${HOST_PIDFILE}
		daemon_watchdog_start_process "${ENVIRON}" "${START_SCRIPT}"
		return $?
	fi

	# Check if the process is alive
	if ! ${KILL} -0 ${PID}; then
		daemon_log_info "$NAME was not running"
		daemon_watchdog_start_process "${ENVIRON}" "${START_SCRIPT}"
		return $?
	fi

	return 0
}
