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

USE_PROCD=1
START=95
STOP=10

. /lib/functions.sh

HONK_CONTROL=/usr/share/honk/control.sh
HONK_CONFIG=/etc/honk/config.dae

boot() {
	local boot_enabled
	config_load honk
	config_get_bool boot_enabled main boot_enabled 0
	[ "$boot_enabled" -eq 1 ] || return 0
	uci set honk.main.enabled='1' || return 1
	uci commit honk || return 1
	start
}

start_service() {
	local enabled initialized config_file
	config_load honk
	config_get_bool enabled main enabled 0
	config_get_bool initialized main initialized 0
	[ "$enabled" -eq 1 ] && [ "$initialized" -eq 1 ] || {
		logger -t honk "refusing to start before explicit initialization and enablement"
		return 1
	}
	config_get config_file main config_file "$HONK_CONFIG"
	[ "$config_file" = "$HONK_CONFIG" ] || {
		logger -t honk "refusing non-default config path"
		return 1
	}
	"$HONK_CONTROL" preflight || return 1
	unset HONK_MAINT_CAP

	procd_open_instance main
	procd_set_param command /usr/bin/honk-core --config "$HONK_CONFIG" --disable-timestamp
	procd_set_param env DAE_LOCATION_ASSET="/usr/share/v2ray"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn 3600 5 5
	procd_set_param term_timeout 20
	procd_close_instance
}

reload_service() {
	# honk-core has no hot-reload API wired here; a reload is an explicit
	# restart so existing connections are cycled. The UI only exposes
	# restart, this exists so manual `/etc/init.d/honk reload` is defined.
	logger -t honk "reload requested, restarting (no hot-reload)"
	restart
}
