#!/bin/sh

. /etc/init.d/globals
. /etc/init.d/functions

# Neutrino's exit action file
ACTION_FILE="${NEUTRINO_EXIT_ACTION_FILE:-/tmp/neutrino.exit-action}"

export NEUTRINO_EXIT_CODES=posix
#export NEUTRINO_EXIT_CODES=legacy

# Neutrino's legacy exit codes
ERROR=-1
NORMAL=0
POWEROFF=1
REBOOT=2
RESTART=3

# if neutrino crashes, just restart it or reboot the box?
case "$(get_boxmodel)" in
	nevis|apollo|shiner|kronos|kronos_v2)
		REBOOT_ON_ERROR=true
	;;
	*)
		REBOOT_ON_ERROR=false
	;;
esac

do_cleanup() {
	# remove files created by neutrino
	rm -f /tmp/.timer "$ACTION_FILE"
}

do_poweroff() {
	display_msg "N: POWEROFF"
	poweroff
}

do_reboot() {
	display_msg "N: REBOOT"
	reboot
}

do_restart() {
	display_msg "N: RESTART"
}

while true; do
	do_cleanup

	if [ -e /var/etc/.coredump ]; then
		# unlimit core file size
		ulimit -c unlimited
	fi

	neutrino; RET=$?
	LOGINFO "Neutrino exited with exit code $RET (NEUTRINO_EXIT_CODES=$NEUTRINO_EXIT_CODES)"

	ACTION=""
	if [ -r "$ACTION_FILE" ]; then
		read -r ACTION < "$ACTION_FILE"
		rm -f "$ACTION_FILE"
	fi

	if [ -z "$ACTION" ]; then
		# legacy fallback: the exit code carries the action
		case "$RET" in
			$NORMAL)	ACTION=none ;;
			$POWEROFF)	ACTION=poweroff ;;
			$REBOOT)	ACTION=reboot ;;
			$RESTART)	ACTION=restart ;;
			*)		ACTION=panic ;;
		esac
	fi
	LOGINFO "Neutrino's exit action is \"$ACTION\""

	case "$ACTION" in
		none)
			# do nothing
			break
		;;
		poweroff)
			do_poweroff
			break
		;;
		reboot)
			do_reboot
			break
		;;
		restart)
			do_restart
			continue
		;;
		panic)
			# continue the script
		;;
		*)
			# ignore unknown exit action
			break
		;;
	esac

	display_msg "N: PANIC $RET"

	# report errors on external display
	if [ -e /tmp/.lcd-* -a -e /tmp/lcd ]; then
		echo "0"		> /tmp/lcd/mode_logo
		echo "Neutrino"		> /tmp/lcd/service
		echo "Error: $RET"	> /tmp/lcd/event
	fi

	if $REBOOT_ON_ERROR; then
		LOGINFO "Rebooting due to REBOOT_ON_ERROR=true and exit code $RET"
		do_reboot
		break
	fi

	LOGINFO "Restarting Neutrino after exit code $RET"
done
