#!/bin/sh
#
# Created by: Mark Felder <feld@FreeBSD.org>

# PROVIDE: unifi
# REQUIRE: LOGIN
# KEYWORD: shutdown

#
# Add the following line to /etc/rc.conf to enable `unifi':
#
# unifi_enable="YES"
#
# Other configuration settings for unifi that can be set in /etc/rc.conf:
#
# unifi_user (str)
#   This is the user that unifi runs as
#   Set to %%USERS%% by default
#
# unifi_group (str)
#   This is the group that unifi runs as
#   Set to %%GROUPS%% by default
#
# unifi_chdir (str)
#   This is the directory that unifi chdirs into before starting
#   Set to %%JAVASHAREDIR%%/unifi by default
#
# unifi_java_home (str)
#   The path to the base directory for the Java to use to run unifi
#   Defaults to %%JAVA_HOME%%
#
# unifi_javaflags (str)
#   Flags passed to Java to run unifi
#   Set to "-Djava.awt.headless=true -Xmx1024M" by default
#

. /etc/rc.subr
name=unifi

rcvar=unifi_enable
load_rc_config ${name}

: ${unifi_enable:=NO}
: ${unifi_user:=%%USERS%%}
: ${unifi_group:=%%GROUPS%%}
: ${unifi_chdir=%%JAVASHAREDIR%%/unifi}
: ${unifi_java_home=%%JAVA_HOME%%}
: ${unifi_javaflags="-Djava.awt.headless=true \
	-Djava.net.preferIPv4Stack=false \
	-Dapple.awt.UIElement=true \
	-Dfile.encoding=UTF-8 \
	-Xmx1024M \
	--add-opens java.base/java.lang=ALL-UNNAMED \
	--add-opens java.base/java.time=ALL-UNNAMED \
	--add-opens java.base/sun.security.util=ALL-UNNAMED \
	--add-opens java.base/java.io=ALL-UNNAMED \
	--add-opens java.rmi/sun.rmi.transport=ALL-UNNAMED"}

pidfile="/var/run/unifi/${name}.pid"
procname=${unifi_java_home}/bin/java
command=/usr/sbin/daemon
command_args="-f -p ${pidfile} ${unifi_java_home}/bin/java ${unifi_javaflags} -jar lib/ace.jar start"
start_precmd=start_precmd
stop_precmd=stop_precmd
stop_postcmd=stop_postcmd

export CLASSPATH=$(echo ${unifi_chdir}/lib/*.jar | tr ' ' ':')

start_precmd()
{
	if [ ! -e /var/run/unifi ] ; then
		install -d -o %%USERS%% -g %%GROUPS%% /var/run/unifi;
	fi
}

stop_precmd()
{
	if [ -r ${pidfile} ]; then
		_UNIFIPID=$(check_pidfile ${pidfile} ${procname})
		export _UNIFI_CHILDREN=$(pgrep -P ${_UNIFIPID})
	fi
}

stop_postcmd()
{
	if ! [ -z ${_UNIFI_CHILDREN} ]; then
		echo "Cleaning up leftover child processes."
		kill $sig_stop ${_UNIFI_CHILDREN}
		wait_for_pids ${_UNIFI_CHILDREN}
	fi
}

run_rc_command "$1"
