#!/bin/ksh
#
# ogmaprotect_setup — firstboot + convergence one-shot (Phase 10.E1 S2)
#
# NOT a supervised daemon: this runs the two-loop provisioner ogmaprotect-setup to
# completion at boot, then exits. It must be enabled LAST in pkg_scripts (AFTER
# ogmaprotect_authd) so that (1) loop 1's admin-seed reaches a live authd, and (2)
# it is the SOLE, LAST starter of httpd/slowcgi — the management plane never binds
# *:443 before the fail-closed pf ruleset is loaded. httpd is deliberately NOT
# `rcctl enable`d; base /etc/rc must never early-start it (that is the whole point).
#
# A non-daemon rc.d helper: allow-listed in scripts/check-daemon-inventory.sh
# (RC_HELPERS), exactly as ogmaprotectctl/ogmaprotect-webhook/... are non-daemon
# sbin helpers on the binary side. It is intentionally NOT in the daemon inventory.

daemon="/usr/local/sbin/ogmaprotect-setup"
daemon_flags="all"

rc_pre() {
	# Best-effort wait for authd's control socket before provisioning. loop 1's
	# admin-seed (when a password is injected) and loop 2's admin-gate both talk to
	# authd, which publishes its socket asynchronously (rc_bg=YES) and can lag this
	# one-shot's start even with a correct boot order. Mirrors ogmaprotect_authd's
	# netd wait, but NON-aborting: a slow authd must not skip cert/chroot/httpd.conf
	# convergence, and ogmaprotect-setup degrades gracefully (the seed defers, the
	# admin-gate defers httpd) when authd is genuinely down. Bounded so a permanently
	# dead authd cannot stall boot.
	_ogma_wait=0
	while ! test -S /var/www/run/ogmaprotect.sock; do
		_ogma_wait=$((_ogma_wait + 1))
		[ $_ogma_wait -gt 30 ] && break
		sleep 1
	done
	return 0
}

rc_start() {
	# Run the provisioner to completion in the FOREGROUND (not backgrounded): it must
	# finish — including loading the fail-closed pf and starting httpd as its final
	# step — before boot proceeds. Its exit status becomes start's (ok)/(failed).
	# pkg_scripts failures do not halt boot, so a failed provision still leaves a
	# booted, SSH-reachable box with httpd NOT started (fail-closed).
	${daemon} ${daemon_flags}
}

rc_check() {
	# One-shot: no persistent process. Report "not running" so `rcctl start` re-runs
	# it every boot (loop 2 is level-triggered convergence; loop 1 is existence-gated
	# so re-runs are cheap no-ops) and `rcctl check` never falsely claims it is up.
	return 1
}

rc_stop() {
	return 0
}

. /etc/rc.d/rc.subr

rc_cmd $1
