#!/usr/bin/env bash
set -euo pipefail

VENV_DIR="/opt/venv/epc670"
REQUIRED_PIP_PKGS=(
    "epc-tofcam-toolkit"
    "epc-tof-studio"
    "epc-tofcam-native"
)
REQUIRED_VENV_BINS=(
    "tofcam670"
    "epc-tof-studio"
)
EPC670_NOTIFIER="/usr/lib/epc670-tofhat-utils/epc670-notifier"
FIRSTBOOT_STAMP="/var/lib/epc670-tofhat-utils/first-boot.done"
TOF_STUDIO_SERVICE="epc-tof-studio.service"

# Per-user marker — must live somewhere the user can write, not root-owned /var/lib
USER_HOME=$(getent passwd "$USER" | cut -d: -f6)
STATE_DIR="${XDG_STATE_HOME:-$USER_HOME/.local/state}/epc670"
FIRSTBOOT_WAITED="$STATE_DIR/firstboot.waited"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
log() { echo "[tofcam670-launcher] $*"; }

warn() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    printf "║  WARNING: %-52s ║\n" "$1"
    printf "║  %-62s ║\n" "$2"
    printf "║  %-62s ║\n" "$3"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
}

# ---------------------------------------------------------------------------
# First-boot gate: wait for /var/lib/epc670-tofhat-utils/first-boot.done (once, max 90s)
# ---------------------------------------------------------------------------

if [ ! -f "$FIRSTBOOT_WAITED" ]; then
    if [ ! -f "$FIRSTBOOT_STAMP" ]; then
        log "First boot detected — waiting for $FIRSTBOOT_STAMP (max 90s)..."
        SECONDS_WAITED=0
        while [ ! -f "$FIRSTBOOT_STAMP" ] && [ "$SECONDS_WAITED" -lt 90 ]; do
            sleep 1
            SECONDS_WAITED=$((SECONDS_WAITED + 1))
        done
        if [ -f "$FIRSTBOOT_STAMP" ]; then
            log "First-boot setup complete after ${SECONDS_WAITED}s."
        else
            log "Warning: timed out after 90s waiting for first-boot stamp."
        fi
    fi
    # Mark that we have done the first-boot wait so we never block again
    mkdir -p "$STATE_DIR"
    touch "$FIRSTBOOT_WAITED"
fi

# ---------------------------------------------------------------------------
# Resolve display
# ---------------------------------------------------------------------------
export DISPLAY="${DISPLAY:-:0}"
export XAUTHORITY="${USER_HOME}/.Xauthority"

# ---------------------------------------------------------------------------
# Preflight checks
# ---------------------------------------------------------------------------
PREFLIGHT_OK=true

# Check for connected physical display
DISPLAY_CONNECTED=false
for connector in /sys/class/drm/card*-*/status; do
    if [ -f "$connector" ] && [ "$(cat "$connector")" = "connected" ]; then
        DISPLAY_CONNECTED=true
        break
    fi
done

if [ "$DISPLAY_CONNECTED" = false ]; then
    warn \
        "No display connected to this device." \
        "Please connect a monitor and try again." \
        ""
    PREFLIGHT_OK=false
fi

# Check venv exists
if [ "$PREFLIGHT_OK" = true ]; then
    if [ ! -f "$VENV_DIR/bin/activate" ]; then
        warn \
            "Python virtual environment not found." \
            "Expected: $VENV_DIR" \
            "Fix: sudo apt install --reinstall epc670-tofhat-utils"
        PREFLIGHT_OK=false
    fi
fi

# Check required pip packages are installed
if [ "$PREFLIGHT_OK" = true ]; then
    for required_pip_pkg in "${REQUIRED_PIP_PKGS[@]}"; do
        if ! "$VENV_DIR/bin/python" -m pip show "$required_pip_pkg" >/dev/null 2>&1; then
            warn \
                "$required_pip_pkg not found in venv." \
                "Expected: $VENV_DIR/bin/python -m pip show $required_pip_pkg" \
                "Fix: sudo apt install --reinstall epc670-tofhat-utils"
            PREFLIGHT_OK=false
            break
        fi
    done
fi

# Check required pip package entry points are installed
if [ "$PREFLIGHT_OK" = true ]; then
    for required_venv_bin in "${REQUIRED_VENV_BINS[@]}"; do
        if [ ! -x "$VENV_DIR/bin/$required_venv_bin" ]; then
            warn \
                "$required_venv_bin entry point not found in venv." \
                "Expected: $VENV_DIR/bin/$required_venv_bin" \
                "Fix: sudo apt install --reinstall epc670-tofhat-utils"
            PREFLIGHT_OK=false
            break
        fi
    done
fi

if [ "$PREFLIGHT_OK" = false ]; then
    echo "One or more required components are missing."
    echo "Please follow the corrective actions above and try again."
    echo ""
    printf "Press Enter to close..."
    read -r _
    exit 1
fi

# ---------------------------------------------------------------------------
# Run epc670-notifier
# ---------------------------------------------------------------------------

log "Checking for updates..."
"$EPC670_NOTIFIER" || true

# ---------------------------------------------------------------------------
# Launch TOFcam GUI
# ---------------------------------------------------------------------------
USE_STUDIO_IP=false
log "Checking epc-tof-studio service status..."
if systemctl is-active --quiet "$TOF_STUDIO_SERVICE"; then
    USE_STUDIO_IP=true
else
    warn \
        "$TOF_STUDIO_SERVICE is not active." \
        "Expected: systemctl is-active $TOF_STUDIO_SERVICE" \
        "Starting TOFcam without --ip=127.0.0.1"
fi

log "Starting TOFcam GUI, this may take a few seconds..."
cd "$USER_HOME"
if [ "$USE_STUDIO_IP" = true ]; then
    exec "$VENV_DIR/bin/tofcam670" --fullscreen --start-stream --ip=127.0.0.1
else
    exec "$VENV_DIR/bin/tofcam670" --fullscreen --start-stream
fi