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

. /etc/rc.subr

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

load_rc_config $name

: ${tidepoolchain_indexer_enable:="NO"}
: ${tidepoolchain_indexer_user="tidepool"}
: ${tidepoolchain_indexer_conf="/usr/local/etc/tidepoolchain/settings.ini"}
: ${tidepoolchain_indexer_mode="sync"}
: ${tidepoolchain_indexer_health_file="/var/run/${name}/${name}.health"}
: ${tidepoolchain_indexer_vault_dir="/var/run/bao"}

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

procname="/usr/local/libexec/tidepoolchain/chain-indexer.php"
command_interpreter="/usr/local/bin/php"
command="/usr/sbin/daemon"
command_args="-p ${pidfile} -o ${logfile} -S -T ${name} -- ${procname} --mode=${tidepoolchain_indexer_mode} --conf=${tidepoolchain_indexer_conf} --health-file=${tidepoolchain_indexer_health_file} --vault-dir=${tidepoolchain_indexer_vault_dir}"

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

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

    # Create log file owned by service user
    install -o ${tidepoolchain_indexer_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 ${tidepoolchain_indexer_user} -m 640 /dev/null "${_health_file}" 2>/dev/null || true

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

    if ! /usr/local/bin/php -m | grep -q gmp; then
        err 1 "PHP gmp extension not installed (required for address derivation)"
    fi
}

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

tidepoolchain_indexer_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"
