#!/usr/bin/env bash
# Build static mobile export + serve on :3005 for Tauri Android/iOS WebView.
# Next.js dev (webpack HMR) is unreliable in the Android WebView — chunks often
# never execute, leaving the SSR boot screen stuck forever.
set -euo pipefail
SUITE_APP="${1:?suite app (mail|drive|agenda|chat|contacts)}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
export NEXT_PUBLIC_SUITE_APP="$SUITE_APP"

MIDDLEWARE="$REPO_ROOT/middleware.ts"
MIDDLEWARE_OFF="$REPO_ROOT/middleware.web.ts"
restore_middleware() {
  if [[ -f "$MIDDLEWARE_OFF" && ! -f "$MIDDLEWARE" ]]; then
    mv "$MIDDLEWARE_OFF" "$MIDDLEWARE"
  fi
}
trap restore_middleware EXIT INT TERM

if [[ -f "$MIDDLEWARE_OFF" && ! -f "$MIDDLEWARE" ]]; then
  mv "$MIDDLEWARE_OFF" "$MIDDLEWARE"
fi
if [[ -f "$MIDDLEWARE" ]]; then
  mv "$MIDDLEWARE" "$MIDDLEWARE_OFF"
fi

echo "[mobile] Building static export (suite=$SUITE_APP)…"
pnpm -C "$REPO_ROOT" build:mobile

echo "[mobile] Serving out/ on http://0.0.0.0:3005 for Tauri WebView…"
exec pnpm dlx serve@14 "$REPO_ROOT/out" -l "tcp://0.0.0.0:3005" --no-clipboard
