#!/usr/bin/env bash
# Launch the desktop shell on the host.
#
# Electron and Tauri need a GUI, which Docker has none of, so the renderer runs
# in the container (the `desktop` service) and the shell runs here, pointed at
# it through DESKTOP_RENDERER_URL.
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

if ! desktop_enabled; then
  echo "error: desktop is off — set RUN_DESKTOP=true and DESKTOP_STACK in run/.env" >&2
  exit 1
fi

APP="${DESKTOP_APP:-desktop}"
URL="http://localhost:${DESKTOP_PORT:-5176}"

COMMAND="${DESKTOP_HOST_CMD:-}"
if [ -z "${COMMAND}" ]; then
  case "${DESKTOP_STACK:-none}" in
    electron) COMMAND="pnpm --filter ${APP} exec electron ." ;;
    tauri)    COMMAND="pnpm --filter ${APP} exec tauri dev" ;;
    *)
      echo "error: set DESKTOP_STACK=electron|tauri (or DESKTOP_HOST_CMD) in run/.env" >&2
      exit 1
      ;;
  esac
fi

if ! command -v pnpm >/dev/null 2>&1 && [ -z "${DESKTOP_HOST_CMD:-}" ]; then
  echo "error: pnpm is not on PATH — the desktop shell runs on the host, not in Docker" >&2
  exit 1
fi

echo "[desktop] renderer ${URL}"
echo "[desktop] ${COMMAND}"
cd "${FRONTEND_DIR}" || exit 1
export DESKTOP_RENDERER_URL="${URL}"
exec bash -lc "${COMMAND}"
