#!/bin/ksh
# Copyright (c) 2026 Wireless Connect Ltd. <https://wirelessconnect.ie>
# SPDX-License-Identifier: PolyForm-Small-Business-1.0.0

#
# ogmaprotect_rcdone — the END-OF-LOOP one-shot (10.F21 S1, PHASE10-F21 §5.3,
# D21, Q15 ratified; the ogmaprotect_setup shape)
#
# NOT a supervised daemon. /etc/rc starts pkg_scripts in SERIES, and a
# per-domain service instance (unbound_rd<N>, dhcpd_rd<N> and, since 10.F24,
# bgpd_rd<N>, made by ogmaprotect-rcinstance from the base script) is a
# base-script copy with no rc_bg, so 255 of
# them take minutes; dnsd's tick runs inside that window and a walk racing the
# loop's tail would double-start an instance /etc/rc is about to start. This
# script is kept LAST in pkg_scripts by every walk (and re-appended by
# deploy.py after its `rcctl order`), so when /etc/rc reaches it the loop is
# over: its start touches the boot-scoped marker under /var/run/ogmaprotect
# (wiped at every boot) and exits; dnsd gates its instance walk on one
# access(2) of that marker, with the box's uptime as the fallback.
#
# The SHUTDOWN FENCE (10.F22 §5.12 (11), its Q12): /etc/rc shutdown walks
# pkg_scripts in REVERSE, so this script is the FIRST it stops — rc_check tests
# the marker and rc_stop removes it, so `stop` passes rc.subr's `rc_check ||
# exit 0` and the marker is gone before the first instance's stop line; a walk
# batch that finds *canonical enabled, not running* meanwhile skips every start
# arm (seen-then-gone = fenced), and a re-touch re-opens it.
#
# rc.subr refuses a script with `daemon` unset (S0 (e): "daemon is not set",
# rc 1 for check and start) and builds pexp from it, so daemon= is set to
# touch with the marker as its only flag; rc_reload=NO so a `reload` sends no
# pkill. Outside INRC a plain `rcctl start` is a silent no-op while the marker
# stands (rc_check says running); `rcctl -f restart ogmaprotect_rcdone` or a
# `stop` then `start` re-touch it — the documented re-arm. On a booted box
# `rcctl check ogmaprotect_rcdone` reads ok, so it never lists under
# `rcctl ls failed`; a fenced (shutting-down) box lists it — the operator's
# tell. Allow-listed in scripts/check-daemon-inventory.sh (RC_HELPERS); the
# marker path is one macro in daemon/common/ogmaprotect.h (OGMA_RCDONE_MARKER)
# that t/rcdone_shape.t greps this line against.

daemon="/usr/bin/touch"
daemon_flags="/var/run/ogmaprotect/rc-pkg-scripts-done"
rc_reload=NO

rc_start() {
	# The parent may not exist yet on a box where no product daemon has
	# created it this boot; the touch runs in the FOREGROUND and its exit
	# status becomes start's (ok)/(failed).
	mkdir -p /var/run/ogmaprotect
	${daemon} ${daemon_flags}
}

rc_check() {
	# "running" iff the marker stands: a plain `rcctl start` while it
	# does is a no-op, and `stop` removes it (the fence).
	test -e ${daemon_flags}
}

rc_stop() {
	rm -f ${daemon_flags}
}

. /etc/rc.d/rc.subr

rc_cmd $1
