#!/bin/sh
#
# PROVIDE: tidepoolbridge
# REQUIRE: LOGIN redis
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf to enable tidepoolbridge:
#
# tidepoolbridge_enable="YES"
#
# Configuration is read from settings.ini.
# Override config path with: tidepoolbridge_conf="/path/to/settings.ini"

. /etc/rc.subr

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

load_rc_config $name

: ${tidepoolbridge_enable:="NO"}
: ${tidepoolbridge_user="tidepool"}
: ${tidepoolbridge_conf="/usr/local/etc/tidepoolbridge/settings.ini"}

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

procname="/usr/local/libexec/tidepoolbridge/zmq-bridge.php"
command_interpreter="/usr/local/bin/php"
command="/usr/sbin/daemon"
command_args="-p ${pidfile} -o ${logfile} -S -T ${name} -- ${procname}"

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

tidepoolbridge_prestart()
{
    # Create PID directory owned by service user
    install -d -o ${tidepoolbridge_user} -m 755 /var/run/${name}

    # Create log file owned by service user
    install -o ${tidepoolbridge_user} -m 640 /dev/null ${logfile} 2>/dev/null || true

    # Pre-create health file so the service user can write to it
    _health_file="/var/run/${name}/${name}.health"
    install -o ${tidepoolbridge_user} -m 640 /dev/null "${_health_file}" 2>/dev/null || true

    # Export config path for the daemon
    export TIDEPOOLBRIDGE_CONF="${tidepoolbridge_conf}"
    export HEALTH_FILE="${_health_file}"

    if ! /usr/local/bin/php -m | grep -q zmq; then
        err 1 "PHP zmq extension not installed (pkg install php84-pecl-zmq)"
    fi

    if ! /usr/local/bin/php -m | grep -q redis; then
        err 1 "PHP redis extension not installed (pkg install php84-pecl-redis)"
    fi

    if [ ! -f "${tidepoolbridge_conf}" ]; then
        err 1 "Config file not found: ${tidepoolbridge_conf}"
    fi
}

tidepoolbridge_poststop()
{
    _health_file="/var/run/${name}/${name}.health"
    rm -f "${_health_file}"
}

tidepoolbridge_health()
{
    _health_file="/var/run/${name}/${name}.health"
    if [ -f "${_health_file}" ]; then
        cat "${_health_file}"
    else
        echo "No health file found at ${_health_file}"
        return 1
    fi
}

run_rc_command "$1"
