#!/bin/sh /etc/rc.common
#
# shellcheck disable=SC3043 # ash supports local

START=90
STOP=10

PROG=/usr/bin/stdiscosrv
USE_PROCD=1

service_triggers() {
	procd_add_reload_trigger 'stdiscosrv'
}

start_service() {
	config_load 'stdiscosrv'

	local config_name='stdiscosrv'
	local enabled compression cert db_dir db_flush_interval debug http key \
		listen metrics_listen nice user
	local gc maxprocs memlimit

	uci_validate_section 'stdiscosrv' 'stdiscosrv' "$config_name" \
		'compression:bool:0' \
		'cert:string:/etc/stdiscosrv/cert.pem' \
		'db_dir:string:/etc/stdiscosrv/db' \
		'db_flush_interval:string' \
		'debug:bool:0' \
		'enabled:bool:0' \
		'gc:uinteger:0' \
		'group:string:syncthing' \
		'http:bool:0' \
		'key:string:/etc/stdiscosrv/key.pem' \
		'listen:string::8443' \
		'maxprocs:uinteger:0' \
		'memlimit:uinteger:0' \
		'metrics_listen:string' \
		'nice:range(-20,19):0' \
		'user:string:syncthing'

	[ "$enabled" = 1 ] || return 0

	[ -z "$group" ] && group=$(id -gn "$user")

	mkdir -p "$db_dir"
	[ -d "$db_dir" ] && chown -R "$user:$group" "$db_dir"

	procd_open_instance stdiscosrv

	procd_set_param command "$PROG"

	[ "$gc" -le 0 ] || procd_append_param env GOGC="$gc"
	[ "$maxprocs" -le 0 ] || procd_append_param env GOMAXPROCS="$maxprocs"
	[ "$memlimit" -le 0 ] || procd_append_param env GOMEMLIMIT="$memlimit"

	procd_append_param command --cert="$cert"
	[ "$compression" -eq 0 ] || procd_append_param command --compression
	procd_append_param command --db-dir="$db_dir"
	[ -z "$db_flush_interval" ] ||
		procd_append_param command --db-flush-interval="$db_flush_interval"
	[ "$debug" -eq 0 ] || procd_append_param command --debug
	[ "$http" -eq 0 ] || procd_append_param command --http
	procd_append_param command --key="$key"
	procd_append_param command --listen="$listen"
	[ -z "$metrics_listen" ] ||
		procd_append_param command --metrics-listen="$metrics_listen"

	procd_set_param nice "$nice"
	procd_set_param term_timeout 15
	procd_set_param user "$user"
	procd_set_param group "$group"
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1

	procd_close_instance
}

reload_service() {
	stop
	start
}
