#!/usr/bin/env bash
#
# tracker-web-boot.sh — boot/login entrypoint for the fleet web tracker.
#
# Launched by the macOS LaunchAgent (see ./install.sh) so tracker-web auto-starts
# on login and survives crash/reboot via KeepAlive — the supervision a bare
# `next dev` (or deploy-gigafactory.sh --tracker-only) doesn't provide.
#
# It does what launchd's minimal environment needs:
#   1. Repairs PATH so node/pnpm are found.
#   2. Loads JWT_SECRET + co. from platform-service/.env (and optional
#      ~/.tracker-web.env overrides) so the telemetry/health proxies work.
#   3. Points the app at the local platform-service and execs `next dev`.
#
set -uo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd -P)"
WEB_DIR="$(cd -- "$SCRIPT_DIR/.." >/dev/null 2>&1 && pwd -P)"            # dashboards/tracker-web
PS_ENV="$(cd -- "$WEB_DIR/../../services/platform-service" >/dev/null 2>&1 && pwd -P)/.env"

# launchd hands processes a bare PATH — prepend the usual node/pnpm locations.
export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH:-}"

# Backend secret + any other shared config from platform-service/.env, then
# per-machine overrides (~/.tracker-web.env, NOT tracked) which win.
set -a
[ -f "$PS_ENV" ] && . "$PS_ENV"
[ -f "$HOME/.tracker-web.env" ] && . "$HOME/.tracker-web.env"
set +a

# Where the app reaches the fleet backend + which product it scopes to by default.
: "${PLATFORM_API_URL:=http://localhost:4003}"
: "${PLATFORM_SERVICE_URL:=$PLATFORM_API_URL}"
: "${DEFAULT_PRODUCT_ID:=lysnrai}"
: "${PRODUCT_ID:=$DEFAULT_PRODUCT_ID}"
export PLATFORM_API_URL PLATFORM_SERVICE_URL DEFAULT_PRODUCT_ID PRODUCT_ID

echo "[tracker-web-boot] $(date '+%Y-%m-%d %H:%M:%S') starting tracker-web on :3003" \
     "(platform=$PLATFORM_API_URL, product=$DEFAULT_PRODUCT_ID)"

cd "$WEB_DIR"
# exec so the LaunchAgent tracks the real next-dev PID (clean KeepAlive restarts).
# `dev` matches the rest of the local setup; the package script pins --port 3003.
exec pnpm dev
