#!/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"
# tidepoolui_consumer_user="www"
# tidepoolui_consumer_dir="/usr/local/www/tidepoolui"
# tidepoolui_consumer_kafka_brokers="localhost:9092"
# tidepoolui_consumer_kafka_topic="tidepool.prod.shares"
# tidepoolui_consumer_kafka_group="tidepoolui-consumer"

. /etc/rc.subr

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

load_rc_config $name

: ${tidepoolui_consumer_enable:="NO"}
: ${tidepoolui_consumer_user:="www"}
: ${tidepoolui_consumer_dir:="/usr/local/www/tidepoolui"}
: ${tidepoolui_consumer_kafka_brokers:="localhost:9092"}
: ${tidepoolui_consumer_kafka_topic:="tidepool.prod.shares"}
: ${tidepoolui_consumer_kafka_group:="tidepoolui-consumer"}
: ${tidepoolui_consumer_health_file:="/var/run/tidepoolui-consumer.health"}
: ${tidepoolui_consumer_max_memory:="128"}

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

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

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

tidepoolui_consumer_prestart()
{
    export KAFKA_BROKERS="${tidepoolui_consumer_kafka_brokers}"
    export KAFKA_TOPIC="${tidepoolui_consumer_kafka_topic}"
    export KAFKA_GROUP="${tidepoolui_consumer_kafka_group}"
    export HEALTH_FILE="${tidepoolui_consumer_health_file}"
    export MAX_MEMORY_MB="${tidepoolui_consumer_max_memory}"
    
    # Ensure log file exists and is writable
    touch ${logfile}
    chown ${tidepoolui_consumer_user}:${tidepoolui_consumer_user} ${logfile}
    
    # Check dependencies
    if ! /usr/local/bin/php -m | grep -q rdkafka; then
        echo "Error: PHP rdkafka extension not installed"
        return 1
    fi
    
    if ! service redis status > /dev/null 2>&1; then
        echo "Warning: Redis may not be running"
    fi
}

tidepoolui_consumer_poststop()
{
    rm -f ${tidepoolui_consumer_health_file}
}

tidepoolui_consumer_status()
{
    if [ -f ${pidfile} ]; then
        pid=$(cat ${pidfile})
        if ps -p ${pid} > /dev/null 2>&1; then
            echo "${name} is running as pid ${pid}"
            return 0
        fi
    fi
    echo "${name} is not running"
    return 1
}

tidepoolui_consumer_health()
{
    if [ -f ${tidepoolui_consumer_health_file} ]; then
        cat ${tidepoolui_consumer_health_file}
    else
        echo "No health file found at ${tidepoolui_consumer_health_file}"
        return 1
    fi
}

run_rc_command "$1"
