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

USE_PROCD=1
START=99

CONF="v2ray"
PROG="/usr/bin/v2ray"

start_service() {
	config_load "$CONF"

	local enabled
	config_get_bool enabled "enabled" "enabled" "0"
	[ "$enabled" -eq "1" ] || return 1

	local confdir
	local conffiles
	local datadir
	local format

	config_get confdir "config" "confdir"
	config_get conffiles "config" "conffiles"
	config_get datadir "config" "datadir" "/usr/share/v2ray"
	config_get format "config" "format" "json"
	config_get_bool memconservative "config" "memconservative" "1"

	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"
	procd_set_param env v2ray.local.asset="$datadir"
	[ "$memconservative" -eq "1" ] && procd_append_param env V2RAY_CONF_GEOLOADER="memconservative"
	procd_set_param file $conffiles

	procd_set_param limits core="unlimited"
	procd_set_param limits nofile="1000000 1000000"
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
