#!/usr/bin/env bash
# Start Next.js mobile dev server from repo root (cwd-independent).
# Temporarily disables root middleware.ts — incompatible with output:export.
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

exec pnpm -C "$REPO_ROOT" dev:mobile
