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

START=90
STOP=10

USE_PROCD=1

PROG=/usr/bin/syncthing

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

	option_cb() {
		local option="$1"
		local value="$2"
		case $option in
		enabled|macprocs|nice|user|logfile)
			eval $option=$value
			;;
		debug)
			extra_args="$extra_args --${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 "syncthing"
}

start_service() {
	local extra_args="--no-browser"

	# Options with default value different with the syncthing should be defined explicitly here
	local enabled=0
	local gui_address="http://0.0.0.0:8384"
	local home="/etc/syncthing"
	local logfile="/etc/syncthing/syncthing.log"
	local macprocs=0
	local nice=0
	local user="syncthing"

	config_load "syncthing"

	# Some of the default values below might not match the defaults
	#   in /etc/config/syncthing: the reason is to remain backwards
	#   compatible with the older versions of this service as it
	#   evolves.
	[ "$enabled" -gt 0 ] || return 0

	# For backwards compatibility
	IDX_DB=$(readlink -n "$home"/index-v0.14.0.db)
	if [ ! -z "$IDX_DB" ]; then
		[ -d "$IDX_DB" ] || mkdir -p "$IDX_DB"

		# A separate step to handle an upgrade use case
		[ -d "$IDX_DB" ] && chown -R $user:$user "$IDX_DB"
	fi

	[ -d "$home" ] || mkdir -p "$home"
	# A separate step to handle an upgrade use case
	[ -d "$home" ] && chown -R $user:$user "$home"

	# Changes to "niceness"/macprocs are not picked up by "reload_config"
	#   nor by "restart": the service has to be stopped/started
	#   for it to take effect
	if [ $macprocs -le 0 ]; then
		# Default to the number of cores in this case
		macprocs=$(grep -c ^processor /proc/cpuinfo)
	fi

	procd_open_instance
	procd_set_param command "$PROG"
	procd_set_param env GOMAXPROCS="$macprocs" STNOUPGRADE=1
	procd_append_param command serve
	procd_append_param command --gui-address="$gui_address"
	procd_append_param command --home="$home"
	procd_append_param command --logfile="$logfile"
	[ -z "$extra_args" ] || procd_append_param command $extra_args

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

reload_service() {
	stop
	start
}