#!/bin/sh /etc/rc.common
# shellcheck shell=dash disable=SC2034  # START/STOP/USE_PROCD are read by /etc/rc.common
# Dawnline: AmneziaWG access server — agent and personal portal.

START=95
STOP=10
USE_PROCD=1

PORTAL_ROOT=/usr/share/dawnline/portal/www

start_portal() {
	local enabled port certs cert key hport http
	config_get_bool enabled settings portal_enabled 0
	[ "$enabled" = 1 ] || return 0
	config_get port settings portal_port 8443
	certs="$(/usr/bin/dawnline portal-cert 2>/dev/null)"
	cert="${certs% *}"
	key="${certs#* }"
	[ -f "$cert" ] && [ -f "$key" ] || return 0
	# IP addresses in links get plain HTTP on the next port (names stay HTTPS-only).
	hport="$(/usr/bin/dawnline portal-http-port 2>/dev/null)"
	[ -n "$hport" ] && http="-p 0.0.0.0:$hport -p [::]:$hport"

	# Portal processes at once: each loads the whole model (a burst of 16 could
	# empty a 128 MB router), so four, and two on a router with little memory;
	# the rest of 64 connections wait their turn.
	local procs=4 mem
	mem="$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo 2>/dev/null)"
	[ -n "$mem" ] && [ "$mem" -le 160 ] && procs=2
	procd_open_instance portal
	procd_set_param command /usr/sbin/uhttpd -f -h "$PORTAL_ROOT" -x /cgi-bin -E /cgi-bin/portal \
		-D -n "$procs" -N 64 -t 20 -T 30 -k 10 -A 1 \
		-s "0.0.0.0:$port" -s "[::]:$port" -C "$cert" -K "$key" $http
	procd_set_param file "$cert"
	procd_set_param respawn 3600 5 0
	procd_close_instance
}

# Plain DNS for Home-only tunnel devices (config written by `dawnline apply`).
start_resolver() {
	[ -f /var/etc/dawnline-dns.conf ] || return 0
	procd_open_instance dns
	procd_set_param command /usr/libexec/dawnline/resolver
	procd_set_param file /var/etc/dawnline-dns.conf
	# A new config kills it (dawnline.resolver): back within a second, not five.
	procd_set_param respawn 3600 1 0
	procd_close_instance
}

start_service() {
	config_load dawnline
	mkdir -p /var/run/dawnline
	/usr/bin/dawnline apply >/dev/null 2>&1

	procd_open_instance agent
	procd_set_param command /usr/libexec/dawnline/agent
	procd_set_param respawn 3600 5 0
	procd_set_param stderr 1
	procd_close_instance

	start_portal
	start_resolver
}

# Noted for the service log: the next agent start is a restart, not a crash or a boot.
stop_service() {
	mkdir -p /var/run/dawnline
	date +%s > /var/run/dawnline/agent.stopped
	# Copies procd doesn't know about (started by hand, or left by an older version) go too.
	pgrep -f '^/usr/bin/ucode /usr/libexec/dawnline/agent' | xargs -r kill 2>/dev/null
}

reload_service() {
	/usr/bin/dawnline apply >/dev/null 2>&1
	start
}

service_triggers() {
	procd_add_reload_trigger dawnline
}
