#!/bin/sh

#
# Start watchdog
#
me="[$(printf $0 | xargs basename)]"
NAME="watchdog trigger for development"
PID_FILE=/var/run/watchdog.pid
ENABLED_FILE=/opt/userdata/.wd-enabled
EXE="/sbin/watchdog"

case "$1" in
	start)
		printf "${me} Starting ${NAME} \\n"
		if [ ! -f "${ENABLED_FILE}" ]; then
    	printf "${me} watchdog is disabled.\\n"
      exit 0
		fi

    if start-stop-daemon --start --quiet --exec ${EXE} --make-pidfile --pidfile ${PID_FILE} -- -t 15 /dev/watchdog; then
			printf "${me} Started with pid $(cat ${PID_FILE}).\\n"
		else
			printf "${me} Starting failed.\\n"
		fi

	;;
	stop)
		printf "Stopping ${NAME}. \\n"
		if [ ! -f "${ENABLED_FILE}" ]; then
    	printf "${me} watchdog is disabled.\\n"
      exit 0
		fi

    if start-stop-daemon --stop --quiet --pidfile "${PID_FILE}"; then
      printf "${me} Stopping ${NAME} done. \\n"
    else
      printf "${me} Stopping ${NAME} failed. \\n"
    fi
	;;
	restart|reload)
		printf "${me} Restarting %s is not implemented.\\n" "${NAME}"
	;;
	start-once)
		printf "${me} Starting ${NAME} once ... \\n"
		if start-stop-daemon --start --quiet --exec ${EXE} --make-pidfile --pidfile ${PID_FILE} -- -t 15 /dev/watchdog; then
			printf "${me} started with pid $(cat ${PID_FILE}).\\n"
		else
			printf "${me} starting failed.\\n"
		fi
	;;
	disable)
		printf "${me} Disabling %s ... " "${NAME}"
		rm -f ${ENABLED_FILE}
		if [ -f "${ENABLED_FILE}" ]; then
			printf "failed.\\n"
		else
			printf "done.\\n"
		fi
	;;
	enable)
		printf "${me} Enabling ${NAME} ... "
		touch "${ENABLED_FILE}"
		if [ -f "${ENABLED_FILE}" ]; then
			printf "done.\\n"
		else
			printf "failed.\\n"
		fi
	;;
	*)
		printf "Usage: %s {start|stop|restart|start-once|enable|disable}\\n" "$0"
		exit 1
esac

exit $?
