#!/bin/sh
#
# PROVIDE: tidepoolui_consumer
# REQUIRE: LOGIN redis
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf to enable tidepoolui_consumer:
#
# tidepoolui_consumer_enable="YES"
#
# Configuration is read from the env file (see consumer.env.sample).
# Override with: tidepoolui_consumer_env_file="/path/to/consumer.env"

. /etc/rc.subr

name="tidepoolui_consumer"
rcvar="${name}_enable"

load_rc_config $name

: ${tidepoolui_consumer_enable:="NO"}
: ${tidepoolui_consumer_user="www"}
: ${tidepoolui_consumer_env_file="/usr/local/etc/tidepoolui/consumer.env"}

pidfile="/var/run/${name}.pid"
logfile="/var/log/${name}.log"

procname="/usr/local/www/tidepoolui/backend/bin/share-consumer.php"
command_interpreter="/usr/local/bin/php"
command="/usr/sbin/daemon"
command_args="-p ${pidfile} -o ${logfile} -S -T ${name} \
    -u ${tidepoolui_consumer_user} -- ${procname}"

start_precmd="${name}_prestart"
stop_postcmd="${name}_poststop"
extra_commands="health"
health_cmd="${name}_health"

tidepoolui_consumer_prestart()
{
    install -o ${tidepoolui_consumer_user} -m 640 /dev/null ${logfile} 2>/dev/null || true

    if ! /usr/local/bin/php -m | grep -q rdkafka; then
        err 1 "PHP rdkafka extension not installed"
    fi
}

tidepoolui_consumer_poststop()
{
    _health_file="/var/run/tidepoolui-consumer.health"
    if [ -f "${tidepoolui_consumer_env_file}" ]; then
        . "${tidepoolui_consumer_env_file}"
        _health_file="${HEALTH_FILE:-${_health_file}}"
    fi
    rm -f "${_health_file}"
}

tidepoolui_consumer_health()
{
    _health_file="/var/run/tidepoolui-consumer.health"
    if [ -f "${tidepoolui_consumer_env_file}" ]; then
        . "${tidepoolui_consumer_env_file}"
        _health_file="${HEALTH_FILE:-${_health_file}}"
    fi
    if [ -f "${_health_file}" ]; then
        cat "${_health_file}"
    else
        echo "No health file found at ${_health_file}"
        return 1
    fi
}

run_rc_command "$1"
