#!/usr/bin/with-contenv bashio
# Headroom optimization proxy — lazy backend for Claude Desktop MCP and Claude Code.
declare port=8787
declare backend_port=8789
declare host=127.0.0.1

# The dashboard is unauthenticated. Keep the gate container-local by default and
# bind all interfaces only when the user explicitly opts in and maps port 8787.
if bashio::config.true 'expose_headroom_dashboard'; then
    host=0.0.0.0
fi

if bashio::config.true 'install_headroom'; then
    real_headroom=""
    for candidate in /usr/bin/headroom /lsiopy/bin/headroom; do
        if [ -x "$candidate" ]; then
            real_headroom="$candidate"
            break
        fi
    done
    if [ -n "$real_headroom" ]; then
        # Keep model artifacts persistent, but do not import Headroom or load the
        # model in this longrun. The standard-library gate starts the real proxy
        # on the first request and terminates it after the idle timeout, releasing
        # Python/ONNX/model allocations. HEADROOM_IDLE_TIMEOUT_SECONDS is
        # overridable through env_vars; 900 seconds is the default.
        export HF_HOME="${HOME}/.headroom/hf"
        mkdir -p "$HF_HOME" "${HOME}/.headroom"
        chown abc:abc "${HOME}/.headroom" "$HF_HOME" 2> /dev/null || true
        bashio::log.info "svc-headroom: starting lazy gate on ${host}:${port} (backend ${backend_port}, idle timeout ${HEADROOM_IDLE_TIMEOUT_SECONDS:-900}s)"
        exec s6-setuidgid abc env \
            HEADROOM_REAL_BIN="$real_headroom" \
            HEADROOM_GATE_HOST="$host" \
            HEADROOM_GATE_PORT="$port" \
            HEADROOM_BACKEND_HOST=127.0.0.1 \
            HEADROOM_BACKEND_PORT="$backend_port" \
            HEADROOM_IDLE_TIMEOUT_SECONDS="${HEADROOM_IDLE_TIMEOUT_SECONDS:-900}" \
            HF_HOME="$HF_HOME" \
            /lsiopy/bin/python3 /usr/local/bin/headroom-proxy-gate.py
    fi
fi

bashio::log.info "svc-headroom: install_headroom disabled or headroom not found; idling"
exec sleep infinity
