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

USE_PROCD=1
START=99

CONF="xray"
PROG="/usr/bin/xray"
CAPA_FILE="/etc/capabilities/xray.json"

start_service() {
	config_load "$CONF"

	local enabled
	config_get enabled "enabled" "enabled" "0"
	[ "$enabled" -eq "0" ] && exit 1

	local confdir
	local conffiles
	local datadir
	local dialer
	local format

	config_get confdir "config" "confdir"
	config_get conffiles "config" "conffiles"
	config_get datadir "config" "datadir" "/usr/share/xray"
	config_get dialer "config" "dialer"
	config_get format "config" "format" "json"

	procd_open_instance "$CONF"
	procd_set_param command "$PROG" run
	[ -n "$confdir" ] && procd_append_param command -confdir "$confdir"
	[ -n "$conffiles" ] && {
		for i in $conffiles
		do
			procd_append_param command -config "$i"
		done
	}
	[ -n "$format" ] && procd_append_param command -format "$format"
	[ -n "$dialer" ] && procd_set_param env XRAY_BROWSER_DIALER="$dialer"
	procd_set_param env XRAY_LOCATION_ASSET="$datadir"
	procd_set_param file $conffiles

	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn

	[ -x "/sbin/ujail" -a -e "$CAPA_FILE" ] && {
		procd_add_jail "$CONF"
		procd_set_param capabilities "$CAPA_FILE"
		procd_set_param user nobody
		procd_set_param no_new_privs 1
	}
	procd_close_instance
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
