#!/bin/sh

# PROVIDE: xray-core
# REQUIRE: LOGIN
# KEYWORD: shutdown

# Add these lines to /etc/rc.conf.local or /etc/rc.conf to enable `xray':
#
# xray_enable (bool):			Set to "NO" by default.
#					Set it to "YES" to enable xray
# xray_config (path):			Set to "/usr/local/etc/xray-core" by default
#					Set it to the xray server config
# xray_logdir (path):			Set to "/var/log/xray-core" by default.
#					Set it to the directory of xray log files
# xray_env (str):			Set to "" by default.
#					Set it to the desired environment variables
# xray_syslog_output_enable (str):	Set to YES to enable syslog output
#					Default is "NO". See daemon(8).
# xray_syslog_output_tag (str):		Set syslog tag if syslog enabled.
#					Default is "xray". See daemon(8).
# xray_syslog_output_priority (str):	Set syslog priority if syslog enabled.
#					Default is "notice". See daemon(8).
# xray_syslog_output_facility (str):	Set syslog facility if syslog enabled.
#					Default is "daemon". See daemon(8).

. /etc/rc.subr

name="xray"
rcvar="xray_enable"

load_rc_config "$name"

: ${xray_enable="NO"}
: ${xray_config="/usr/local/etc/${name}-core"}
: ${xray_logdir="/var/log/${name}-core"}
: ${xray_syslog_output_enable:="NO"}
: ${xray_user="v2ray"}
: ${xray_group="v2ray"}

if checkyesno xray_syslog_output_enable; then
	if [ -n "${xray_syslog_output_tag}" ]; then
		xray_syslog_output_flags="-T ${xray_syslog_output_tag}"
	else
		xray_syslog_output_flags="-T ${name}"
	fi
	if [ -n "${xray_syslog_output_priority}" ]; then
		xray_syslog_output_flags="${xray_syslog_output_flags} -s ${xray_syslog_output_priority}"
	fi
	if [ -n "${xray_syslog_output_facility}" ]; then
		xray_syslog_output_flags="${xray_syslog_output_flags} -l ${xray_syslog_output_facility}"
	fi
fi

asset_env="XRAY_LOCATION_ASSET=/usr/local/share/${name}-core"
pidfile="/var/run/$name.pid"
procname="/usr/local/bin/xray"
command="/usr/sbin/daemon"
command_args="-f -t ${name} ${xray_syslog_output_flags} -p ${pidfile} /usr/bin/env ${asset_env} ${xray_env} ${procname} -confdir ${xray_config}"
required_files="${xray_config}"

start_precmd="xray_startprecmd"

xray_startprecmd() {
	touch "${pidfile}"
	chown ${xray_user}:${xray_group} "${pidfile}"
	mkdir -p "${xray_logdir}"
	chown -R ${xray_user}:${xray_group} "${xray_logdir}"
}

run_rc_command "$1"
