#!/bin/sh

# $FreeBSD$
#
# PROVIDE: %%PORTNAME%%
# REQUIRE: NETWORKING SERVERS
# KEYWORD: shutdown
#
# Add these following line to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# %%PORTNAME%%_enable (bool):	Set it to YES to enable keycloak on startup.
#				Default: NO
# %%PORTNAME%%_user (string):	User account to run with.
#				Default: %%USER%%
# %%PORTNAME%%_group (string):	Group for %%LOG_DIR%% and %%RUN_DIR%%.
#				Default: %%GROUP%%
# %%PORTNAME%%_flags (string):	Additional flags for the startup script.
#				Default: start
# %%PORTNAME%%_java_home (string):	JAVA_HOME to run with.
#				Default: %%JAVA_HOME%%
#

. /etc/rc.subr

name=%%PORTNAME%%
rcvar=%%PORTNAME%%_enable
desc="Identity and access management solution"

load_rc_config $name

: ${%%PORTNAME%%_enable:="NO"}
: ${%%PORTNAME%%_user:="%%USER%%"}
: ${%%PORTNAME%%_group:="%%GROUP%%"}
: ${%%PORTNAME%%_flags="start"}
: ${%%PORTNAME%%_java_home="%%JAVA_HOME%%"}
%%PORTNAME%%_env="${%%PORTNAME%%_env} JAVA_HOME=${%%PORTNAME%%_java_home}"

pidfile=%%RUN_DIR%%/%%PORTNAME%%.pid
command=/usr/sbin/daemon
command_args="-u ${%%PORTNAME%%_user} -o %%LOG_DIR%%/%%PORTNAME%%.out -t %%PORTNAME%% -R 60 -P ${pidfile}"

start_cmd="%%PORTNAME%%_start"
stop_cmd="%%PORTNAME%%_stop"
build_cmd="%%PORTNAME%%_build"

%%PORTNAME%%_start()
{
	if [ ! -d "%%LOG_DIR%%" ]; then
		install -d -o ${%%PORTNAME%%_user} -g ${%%PORTNAME%%_group} %%LOG_DIR%%
	fi
	if [ ! -d "%%RUN_DIR%%" ]; then
		install -d -o ${%%PORTNAME%%_user} -g ${%%PORTNAME%%_group} %%RUN_DIR%%
	fi

	chown -R ${%%PORTNAME%%_user}:${%%PORTNAME%%_group} %%LOG_DIR%% %%RUN_DIR%%

	echo "Starting %%PORTNAME%%."
        ${command} ${command_args} \
                %%JAVASHAREDIR%%/%%PORTNAME%%/bin/kc.sh \
                ${%%PORTNAME%%_flags}
}

%%PORTNAME%%_stop()
{
    local pid_daemon
    local pid_child

    echo "Stopping %%PORTNAME%%."

    pid_daemon=$(check_pidfile ${pidfile} ${command})
    if [ ! -z "${pid_daemon}" ]; then
        kill -TERM ${pid_daemon}
    fi

    pid_child=$(pgrep -U ${%%PORTNAME%%_user} -f %%JAVASHAREDIR%%/%%PORTNAME%%/)
    if [ ! -z "${pid_child}" ]; then
        kill -TERM ${pid_child}
    fi

    wait_for_pids ${pid_daemon} ${pid_child}
}

%%PORTNAME%%_build()
{
    su -m ${%%PORTNAME%%_user} -c "%%JAVASHAREDIR%%/%%PORTNAME%%/bin/kc.sh build"
}

extra_commands="build"
run_rc_command "$1"
