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

USE_PROCD=1
START=99

NAME="sing-box"
PROG="/usr/bin/sing-box"

start_service() {
	config_load "$NAME"

	local enabled user group conffile workdir
	config_get_bool enabled "main" "enabled" "0"
	[ "$enabled" -eq "1" ] || return 0

	config_get user "main" "user" "root"
	config_get conffile "main" "conffile"
	config_get workdir "main" "workdir" "/usr/share/sing-box"

	mkdir -p "$workdir"
	local group="$(id -ng $user)"
	chown $user:$group "$workdir"

	procd_open_instance "$NAME.main"
	procd_set_param command "$PROG" run -c "$conffile" -D "$workdir"

	# Use root user if you want to use the TUN mode.
	procd_set_param user "$user"
	procd_set_param file "$conffile"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "$NAME"
}
