#!/sbin/openrc-run
# MarlinOS WAKE edge daemon. OpenRC equivalent of pkg/linux/waked-edge.service.
# OpenRC has no equivalent of systemd's NoNewPrivileges sandboxing directive.
# rc_cgroup_settings is best-effort (only enforced when the host has cgroup2
# available, which Alpine 3.24 does by default) rather than a hard guarantee
# (ADR-0116 accepted gap).

name="waked-edge"
description="WAKE Edge Daemon"
command="/opt/wake/bin/python"
command_args="-m waked -c /var/db/wake/edge/waked.toml"
command_user="wake:wake"
supervisor="supervise-daemon"
respawn_delay=5
pidfile="/run/${RC_SVCNAME}.pid"

rc_ulimit="-n 65536"
rc_cgroup_settings=" memory.max 2G "

depend() {
	need net
	before rsyslog
	use rsyslog
}

start_pre() {
	# systemd's RuntimeDirectory=wake equivalent. /run is tmpfs and empty
	# at every boot, so the unprivileged wake user needs this created
	# before it can bind its socket dir.
	checkpath -d -o wake:wake -m 0755 /run/wake
	# Edge node.key before rsyslog/immesh. start_pre runs as root and
	# the wake account's shell is nologin, so chown after keygen.
	checkpath -d -o wake:wake -m 0750 /var/db/wake/edge
	/opt/wake/bin/python -m waked.keygen /var/db/wake/edge/node.key \
		|| return 1
	chown wake:wake /var/db/wake/edge/node.key
	chmod 0600 /var/db/wake/edge/node.key

	# Fleet delivers per-host secrets here (WAKED_REGISTRATION_TOKEN);
	# optional on a standalone (non-fleet) wake host, mirroring systemd's
	# EnvironmentFile=-/etc/marlinos/secrets.env. `set -a` exports every
	# variable the file defines so supervise-daemon's spawned child
	# actually inherits them (plain `.` only sets them in this script's
	# own shell, which the child does not see). Done here, not at
	# top-level, so `status`/other actions never touch the 0600 file.
	if [ -f /etc/marlinos/secrets.env ]; then
		set -a
		. /etc/marlinos/secrets.env
		set +a
	fi
}
