#!/bin/sh
### BEGIN INIT INFO
# Provides:          zenguser-healthcheck
# Required-Start:    $syslog nginx syscontrol.fcgi
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Verify eng user unlock endpoint is reachable
### END INIT INFO

# If the eng-user-enable endpoint is not reachable after boot, unlock the
# eng user (root) so the device is not permanently locked with no way to
# recover. On a healthy boot EngUserManager will re-lock immediately.

case "$1" in
  start)
	# Give the full stack a moment to settle after nginx starts
	sleep 2

	# Try to reach the security status endpoint through the full
	# nginx -> syscontrol FCGI stack via localhost.
	if curl -sf -o /dev/null -m 5 http://127.0.0.1/daktronics/syscontrol/1.0/utilities/security/status 2>/dev/null; then
		echo "enguser-healthcheck: endpoint reachable, eng user state managed by EngUserManager"
	else
		echo "enguser-healthcheck: WARNING - endpoint NOT reachable, unlocking eng user and starting SSH as failsafe"
		/usr/sbin/usermod --unlock root 2>/dev/null || true
		/etc/init.d/dropbear start 2>/dev/null || true
		logger -p daemon.warning "enguser-healthcheck: unlocked root and started SSH because security endpoint was not reachable at boot"

		# Auto-lock root and stop SSH after 4 hours (does not survive reboot, which is fine
		# because the health check re-evaluates on every boot)
		(sleep 14400; /etc/init.d/dropbear stop; /usr/sbin/usermod --lock root; logger -p daemon.warning "enguser-healthcheck: failsafe timeout expired, re-locked root and stopped SSH") 2>/dev/null &
	fi
	;;

  stop|restart)
	;;

  *)
	echo "Usage: /etc/init.d/zenguser-healthcheck {start|stop|restart}"
	exit 1
	;;
esac

exit 0
