#!/bin/sh
#
# artifactory startup script.
#
# Make sure you have the artifactory user and artifactory home or set them below accordingly!

# PROVIDE: artifactory
# REQUIRE: NETWORKING SERVERS
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable artifactory:
# artifactory_enable (bool):      Set to "YES" to enable artifactory
# artifactory_args (str):         Optional arguments to Artifactory
# artifactory_log_stdout (str)       Artifactory log output stdout, filename.
# artifactory_log_stderr (str)       Artifactory log output stderr, filename.
#

ARTIFACTORY_HOME=%%APP_HOME%%

. /etc/rc.subr

name="artifactory"
rcvar=artifactory_enable

load_rc_config $name

artifactory_enable="${artifactory_enable:-"NO"}"
artifactory_log_stdout="${artifactory_log_stdout:-"${artifactory_logdir}/stdout.log"}"
artifactory_log_stderr="${artifactory_log_stderr:-"${artifactory_logdir}/stderr.log"}"
artifactory_args="${artifactory_args:-""}"
artifactory_sleep="${artifactory_sleep:-"5"}"
artifactory_kill9="${artifactory_kill9:-""}"
artifactory_additional_killall="${artifactory_additional_killall:-""}"
artifactory_user="artifactory"
artifactory_logdir=$ARTIFACTORY_HOME/logs

start_cmd="artifactory_start"
stop_cmd="artifactory_stop"
pidfile=%%PID_FILE%%

artifactory_start ()
{
    if [ ! -d "${artifactory_logdir}" ]
    then
        install -d -o ${artifactory_user} ${artifactory_logdir}
    fi

    echo "Starting artifactory."
    daemon -u ${artifactory_user} ${ARTIFACTORY_HOME}/bin/artifactory.sh ${artifactory_args} >> ${artifactory_log_stdout} 2>> ${artifactory_log_stderr} >> ${artifactory_logdir}/boot.log 2>> ${artifactory_logdir}/boot.log

    sleep ${artifactory_sleep}  # let daemon(8) and sh(1) finish before executing pgrep(1)
    pgrep -U ${artifactory_user} > ${pidfile}
    chown ${artifactory_user} $pidfile
}

artifactory_stop ()
{
    # Subvert the check_pid_file procname check.
    if [ -f ${pidfile} ]
    then
        kill `cat ${pidfile}`
        # Only if we aware that our setup can hangs, and only after trying simple kill, we can kill it hard way.
        if [ ! -z "${artifactory_kill9}" ]
        then
            sleep ${artifactory_sleep}
            kill  -9 `cat ${pidfile}`
        fi
        # In some setups, Artifactory can spawn some child processess, which could prevent it from stopping, and freeing net ports.
        # Let's blindly kill them all, since we are really know what we are doing.
        if [ ! -z "${artifactory_additional_killall}" ]
        then
            sleep ${artifactory_sleep}
            killall ${artifactory_additional_killall}
        fi
    fi
}

run_rc_command "$1"
