#!/bin/sh

# PROVIDE: oauth2_proxy
# REQUIRE: NETWORKING SERVERS
# KEYWORD: shutdown
#
# Add these following line to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# oauth2_proxy_enable (bool):         Set it to YES to enable keycloak on startup.
#                                 Default: NO
# oauth2_proxy_user (string):         User account to run with.
#                                 Default: www
# oauth2_proxy_flags (string):        Additional flags for the startup script.
#

. /etc/rc.subr

name=oauth2_proxy
rcvar=oauth2_proxy_enable
desc="OAuth 2.0 proxy server"

load_rc_config $name

: ${oauth2_proxy_enable:=NO}
: ${oauth2_proxy_user:=www}
: ${oauth2_proxy_group:=www}
: ${oauth2_proxy_flags:=""}
: ${oauth2_proxy_restart:=60}

pidfile=/var/run/oauth2-proxy/oauth2-proxy.pid
command=/usr/sbin/daemon
command_args="-u ${oauth2_proxy_user} -o /var/log/oauth2-proxy/oauth2-proxy.out -t oauth2-proxy -R ${oauth2_proxy_restart} -P ${pidfile}"

start_cmd="oauth2_proxy_start"
stop_cmd="oauth2_proxy_stop"

oauth2_proxy_start()
{
	if [ ! -d "/var/log/oauth2-proxy" ]; then
		install -d -o ${oauth2_proxy_user} /var/log/oauth2-proxy
	fi
	if [ ! -d "/var/run/oauth2-proxy" ]; then
		install -d -o ${oauth2_proxy_user} /var/run/oauth2-proxy
	fi

	chown -R ${oauth2_proxy_user} /var/log/oauth2-proxy

	echo "Starting oauth2-proxy."
        ${command} ${command_args} \
                /usr/local/bin/oauth2-proxy \
                --config /usr/local/etc/oauth2-proxy.cfg \
                ${oauth2_proxy_flags}
}

oauth2_proxy_stop()
{
    local pid_daemon
    local pid_child

    echo "Stopping oauth2-proxy."

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


    pid_child=$(pgrep -U ${oauth2_proxy_user} -f /usr/local/bin/oauth2-proxy)
    if [ ! -z "${pid_child}" ]; then
        kill -TERM ${pid_child}
    fi

    wait_for_pids ${pid_daemon} ${pid_child}
}

run_rc_command "$1"
