#!/bin/ksh
#
# ogmaprotect-authd — authentication gateway (start after netd)

daemon="/usr/local/sbin/ogmaprotect-authd"
rc_bg=YES

ogma_authd_sock_ok() {
	if ! test -S /var/www/run/ogmaprotect.sock; then
		return 1
	fi
	own=$(stat -f '%Su:%Sg' /var/www/run/ogmaprotect.sock 2>/dev/null) || return 1
	test "$own" = "root:www"
}

ogma_ensure_www_run_dir() {
	mkdir -p /var/www/run
	chown root:www /var/www/run 2>/dev/null || return 1
	chmod 770 /var/www/run 2>/dev/null || return 1
	return 0
}

rc_pre() {
	# netd is authd's hard dependency (authd proxies to it; its socket is the
	# apply/restore substrate). netd publishes the socket asynchronously (rc_bg),
	# so even with a correct boot order it can lag authd's start by a moment.
	# Hard-failing here would leave authd DOWN for the whole uptime with no retry
	# (10.A4: that also strands boot recovery). Wait bounded for the socket.
	# deploy.py enforces the netd-first/authd-last boot order; this is
	# defence-in-depth for the publish race.
	_ogma_wait=0
	while ! test -S /var/run/ogmaprotect-netd.sock; do
		_ogma_wait=$((_ogma_wait + 1))
		if [ $_ogma_wait -gt 60 ]; then
			echo "ogmaprotect-netd socket required (waited 60s)"
			return 1
		fi
		sleep 1
	done
	ogma_ensure_www_run_dir || return 1
}

rc_stop() {
	pkill -x ogmaprotect-authd 2>/dev/null || true
	rm -f /var/www/run/ogmaprotect.sock
}

rc_start() {
	# Idempotent only when socket exists, process runs, and www can connect.
	if ogma_authd_sock_ok && pgrep -x ogmaprotect-authd >/dev/null 2>&1; then
		return 0
	fi
	rc_stop
	ogma_ensure_www_run_dir || return 1
	${rc_daemon} ${daemon} ${daemon_flags}
}

. /etc/rc.d/rc.subr

rc_cmd $1
