#!/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"
		case $option in
		enabled|listen|cert|db_dir|key)
			eval $option=$value
			;;
		_*)
			[ "$value" = "0" ] || extra_args="$extra_args -${option//_/-}"
			;;
		*)
			extra_args="$extra_args -${option//_/-}=$value"
			;;
		esac
	}

	list_cb() {
		local name="$1"
		local value="$2"
		[ "$name" = "_" ] && extra_args="$extra_args --${value//_/-}" || return 0
	}
}

service_triggers()
{
	procd_add_reload_trigger "stdiscosrv"
}

start_service() {
	local extra_args
	# Options with default value different with the syncthing should be defined explicitly here
	local enabled=0
	local listen=":8443"
	local cert="/etc/stdiscosrv/cert.pem"
	local key="/etc/stdiscosrv/key.pem"
	local db_dir="/etc/stdiscosrv/discovery.db"
	local nice=0

	config_load "stdiscosrv"

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

	[ -d "$db_dir" ] || mkdir -p "$db_dir"
	[ -d "$db_dir" ] && chown -R nobody:nogroup "$db_dir"

	config_get nice stdiscosrv nice "0"

	procd_open_instance
	procd_set_param command "$PROG"
	procd_append_param command -listen="$listen"
	procd_append_param command -db-dir="$db_dir"
	procd_append_param command -cert="$cert"
	procd_append_param command -key="$key"
	[ -z "$extra_args" ] || procd_append_param command "$extra_args"

	procd_set_param nice "$nice"
	procd_set_param term_timeout 15
	procd_set_param user "nobody"
	procd_set_param respawn
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

reload_service() {
	stop
	start
}
