#!/usr/bin/env bash
# Lumotia dev launcher. Starts Vite first, waits for it to bind port 1420,
# then runs Tauri without triggering a second Vite instance.
# Sets the Linux rendering env vars that warn_if_x11_env_unset_on_wayland
# (src-tauri/src/lib.rs) expects the launcher to own.
# For performance testing use: npm run tauri build
set -euo pipefail
cd "$(dirname "$0")"

case "$(uname -s)" in
    Linux)
        # Bindgen libclang path. Fedora 41/LLVM 21 default; user-set wins.
        export LIBCLANG_PATH="${LIBCLANG_PATH:-/usr/lib64/llvm21/lib64}"
        # iGPU idle-cost workaround. Set to 0 explicitly to opt out.
        export WEBKIT_DISABLE_DMABUF_RENDERER="${WEBKIT_DISABLE_DMABUF_RENDERER:-1}"
        if [ "${XDG_SESSION_TYPE:-}" = "wayland" ]; then
            export GDK_BACKEND="${GDK_BACKEND:-x11}"
            export WINIT_UNIX_BACKEND="${WINIT_UNIX_BACKEND:-x11}"
        fi
        ;;
esac

# Supply-chain pre-flight. Verify npm registry signatures whenever the
# lockfile has changed since the last successful audit. Skip with
# LUMOTIA_SKIP_AUDIT=1 (e.g. offline dev). Fails loud on signature mismatch.
audit_stamp=".lumotia-last-audit"
if [ "${LUMOTIA_SKIP_AUDIT:-0}" != "1" ]; then
    if [ ! -f "$audit_stamp" ] || [ "package-lock.json" -nt "$audit_stamp" ]; then
        printf 'Lockfile changed since last audit. Verifying npm signatures...\n' >&2
        if ! npm audit signatures; then
            printf 'npm audit signatures FAILED. Possible supply-chain compromise. Investigate before launching. Override: LUMOTIA_SKIP_AUDIT=1\n' >&2
            exit 1
        fi
        touch "$audit_stamp"
    fi
fi

printf 'Starting Vite dev server...\n' >&2
npm run dev:frontend &
VITE_PID=$!

cleanup() {
    kill "$VITE_PID" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

# Wait up to 60s for Vite, bailing if it exits early.
for _ in $(seq 1 120); do
    if curl -sf http://localhost:1420 > /dev/null 2>&1; then
        break
    fi
    if ! kill -0 "$VITE_PID" 2>/dev/null; then
        printf 'Vite dev server exited before becoming ready.\n' >&2
        wait "$VITE_PID"
        exit 1
    fi
    sleep 0.5
done

if ! curl -sf http://localhost:1420 > /dev/null 2>&1; then
    printf 'Timed out waiting for Vite on http://localhost:1420\n' >&2
    exit 1
fi

printf 'Vite ready. Launching Tauri...\n' >&2
npx tauri dev --config '{"build":{"beforeDevCommand":""}}' "$@"
