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

START=90
STOP=10

USE_PROCD=1

PROG=/usr/bin/stdiscosrv

config_cb() {
	[ $# -eq 0 ] && return

	option_cb() {
		local option="$1"
		local value="$2"
		# Remove the leading underscore from the option name for backward
		# compatibility
		option="${option#_}"
		eval $option="$value"
	}
}

service_triggers() {
	procd_add_reload_trigger 'stdiscosrv'
}

start_service() {
	local conf_dir='/etc/stdiscosrv'

	# Options with default value different with the syncthing should be defined
	# explicitly here
	local enabled=0
	local compression=0
	local cert="$conf_dir/cert.pem"
	local db_dir="$conf_dir/discovery.db"
	local db_flush_interval=''
	local debug=0
	local http=0
	local key="$conf_dir/key.pem"
	local listen=':8443'
	local metrics_listen=''
	local nice=0
	local user='syncthing'

	config_load 'stdiscosrv'

	[ "$enabled" -gt 0 ] || return 0

	local group=$(id -gn $user)

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

	procd_open_instance

	procd_set_param command "$PROG"
	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
}
