#!/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: www
# %%PORTNAME%%_flags (string):        Additional flags for the startup script.
#                                 Default: start
#

. /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%%"}

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"

export JAVA_HOME=${%%PORTNAME%%_java_home}

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

	chown -R ${%%PORTNAME%%_user} %%LOG_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"
