#!/bin/sh

# PROVIDE: %%PORTNAME%%
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# %%RC_NAME%%_enable:	Set to yes to enable the %%PORTNAME%% service.
#			Default: no
# %%RC_NAME%%_user:	The user account used to run the %%PORTNAME%% daemon.
#			This is optional, however do not specifically set this to an
#			empty string as this will cause the daemon to run as root.
#			Default: %%USER%%
# %%RC_NAME%%_group:	The group account used to run the %%PORTNAME%% daemon.
#			This is optional, however do not specifically set this to an
#			empty string as this will cause the daemon to run with group wheel.
#			Default: %%GROUP%%
# %%RC_NAME%%_data_dir: Directory where %%PORTNAME%% configuration
#			data is stored.
#			Default: /var/db/%%PORTNAME%%
# %%RC_NAME%%_ffdetect: Path of the ffdetect binary.
#			Default: %%PREFIX%%/lib/emby-server/bin/ffdetect
# %%RC_NAME%%_ffmpeg:	Path of the ffmpeg binary.
#			Default: %%PREFIX%%/lib/emby-server/bin/ffmpeg
# %%RC_NAME%%_ffprobe:	Path of the ffprobe binary.
#			Default: %%PREFIX%%/lib/emby-server/bin/ffprobe
# %%RC_NAME%%_pid:	Name of the pid file.
#			Default: %%PORTNAME%%.pid
# %%RC_NAME%%_pid_dir:	Path of the pid file.
#			Default: /var/run/emby-server

. /etc/rc.subr
name=%%RC_NAME%%
rcvar=${name}_enable
load_rc_config ${name}

: ${%%RC_NAME%%_enable:="no"}
: ${%%RC_NAME%%_user:="%%USER%%"}
: ${%%RC_NAME%%_group:="%%GROUP%%"}
: ${%%RC_NAME%%_data_dir:="/var/db/%%PORTNAME%%"}
: ${%%RC_NAME%%_ffdetect:="%%PREFIX%%/lib/emby-server/bin/ffdetect"}
: ${%%RC_NAME%%_ffmpeg:="%%PREFIX%%/lib/emby-server/bin/ffmpeg"}
: ${%%RC_NAME%%_ffprobe:="%%PREFIX%%/lib/emby-server/bin/ffprobe"}
: ${%%RC_NAME%%_pid:="%%PORTNAME%%.pid"}
: ${%%RC_NAME%%_pid_dir:="/var/run/emby-server"}

pidfile="${%%RC_NAME%%_pid_dir}/${%%RC_NAME%%_pid}"
command="/usr/sbin/daemon"
command_args="-r -f -P ${pidfile} %%LOCALBASE%%/bin/dotnet %%PREFIX%%/lib/emby-server/system/EmbyServer.dll \
	-os freebsd \
	-ffdetect ${%%RC_NAME%%_ffdetect} \
	-ffmpeg ${%%RC_NAME%%_ffmpeg} \
	-ffprobe ${%%RC_NAME%%_ffprobe} \
	-programdata ${%%RC_NAME%%_data_dir}"

start_precmd=%%RC_NAME%%_start_precmd
%%RC_NAME%%_start_precmd()
{
	[ -d ${%%RC_NAME%%_pid_dir} ] || install -d -g ${%%RC_NAME%%_group} -o ${%%RC_NAME%%_user} ${%%RC_NAME%%_pid_dir}
	[ -d ${%%RC_NAME%%_data_dir} ] || install -d -g ${%%RC_NAME%%_group} -o ${%%RC_NAME%%_user} ${%%RC_NAME%%_data_dir}

	# .NET 6+ use dual mode sockets to avoid the separate AF handling.
	# disable .NET use of V6 if no ipv6 is configured.
	# See https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=259194#c17
	ifconfig -a -u -G lo | grep -q inet6
	if [ $? == 1 ]; then
		export DOTNET_SYSTEM_NET_DISABLEIPV6=1
	fi

	if [ `uname -K` -ge 1400092 ]; then
		export CLR_OPENSSL_VERSION_OVERRIDE=30
	fi

	export LD_LIBRARY_PATH=%%PREFIX%%/lib/emby-server/lib:%%LOCALBASE%%/lib
}

run_rc_command "$1"
