#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

PROG=/usr/bin/srunnet

extra_command "stop_for_update" "Stop the main service for the independent installer"

stop_for_update() {
	SMARTSRUN_INSTALL_WORKER=1
	stop
}

stop_service() {
	# A direct user stop records the desired final state. Native package hooks
	# inherit this marker from our worker and must not change that intention.
	[ "$SMARTSRUN_INSTALL_WORKER" = "1" ] && return 0
	# The native package manager may be replacing PROG (temporarily even its
	# execute bit). Record user intent through the stable installer copy.
	if [ -x /var/run/smart-srun/update-worker ]; then
		/var/run/smart-srun/update-worker _update-intent stopped
	else
		"$PROG" _update-intent stopped
	fi
}

# Starting this service is not the same as switching automatic authentication
# on. The service answers the local control socket so the interface and the CLI
# can talk to it; whether it authenticates on its own is the `enabled` setting
# inside /etc/smart-srun/config.json, which ships off. Conflating the two is how
# a fresh install starts logging in with credentials nobody has entered yet.
start_service() {
	procd_open_instance instance1
	procd_set_param command "$PROG" daemon

	# retry=0 means unlimited respawn, and it is deliberate. With a finite
	# budget, manual actions that restart the service burn through it -- the
	# Python version's 5-attempt budget was exhausted exactly that way, after
	# which the daemon stayed dead until somebody rebooted the router.
	procd_set_param respawn 3600 5 0

	# The daemon cancels its work, writes its last state snapshot and releases
	# its lock on SIGTERM, and gives a worker that ignores cancellation ten
	# seconds before giving up on it. procd's default five seconds would cut
	# that short and SIGKILL a shutdown that was about to finish.
	procd_set_param term_timeout 15

	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

# procd knows which process it started and stops that one. The Python version
# needed to hunt through /proc because the daemon, the CLI and the update worker
# were all `client.py` and a blunt stop killed installs halfway through. Here
# the update worker is a separate procd service running its own copy of the
# binary, so stopping this service stops this service -- which is what spec 02
# requires and what a process hunt could never guarantee.
