#!/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="tidepool"}
: ${tidepoolui_consumer_group="tidepool"}
: ${tidepoolui_consumer_env_file="/usr/local/etc/tidepoolui/consumer.env"}

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

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

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

tidepoolui_consumer_prestart()
{
    /usr/bin/install -d -o ${tidepoolui_consumer_user} -g ${tidepoolui_consumer_group} -m 755 ${pidfile%/*}
    /usr/bin/install -d -o ${tidepoolui_consumer_user} -g ${tidepoolui_consumer_group} -m 755 /var/log
    if [ ! -f "${logfile}" ]; then
        /usr/bin/install -o ${tidepoolui_consumer_user} -g ${tidepoolui_consumer_group} -m 640 /dev/null ${logfile}
    fi

    # Pre-create health file so the consumer user can write to it
    _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
    /usr/bin/install -o ${tidepoolui_consumer_user} -g ${tidepoolui_consumer_group} -m 640 /dev/null "${_health_file}" 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"
