#!/usr/bin/env bash
#
# Run the Cypress suite locally against the gem's dummy-app backend.
#
# The dummy-app links the LOCAL gem (Gemfile `path:`) and the LOCAL npm package
# (package.json `link:`), so the suite exercises your working copies of both
# glib-web and glib-web-npm -- no gem release needed. This script does what
# doc/TESTING.md describes, in one command: boot the backend, wait for it, run
# Cypress, then tear the backend down.
#
# Usage:
#   scripts/cypress-local.sh                 # run the whole e2e suite
#   scripts/cypress-local.sh open            # interactive Cypress UI
#   scripts/cypress-local.sh --spec cypress/e2e/glib-web/form.cy.js
#   scripts/cypress-local.sh <any cypress args...>
#
# Options (env vars):
#   GLIB_WEB_DIR   path to the glib-web gem checkout   (default: ../glib-web)
#   GLIB_WEB_REF   branch/tag/sha to check out in glib-web before running
#                  (default: leave the current checkout as-is). Requires a
#                  clean working tree; runs `git fetch` then `git checkout`.
#   BACKEND_PORT   port to boot the dummy-app on        (default: 3230)
#   SETUP=1        force (re)install of gem + npm deps before running
#
# If a server is already listening on BACKEND_PORT, the script reuses it and
# does NOT boot or kill one -- so you can keep a server running yourself and
# just re-run specs quickly.

set -euo pipefail

# --- resolve paths (repo root is this script's parent dir) -------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
NPM_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
GLIB_WEB_DIR="$(cd "${GLIB_WEB_DIR:-$NPM_DIR/../glib-web}" 2>/dev/null && pwd || true)"
BACKEND_PORT="${BACKEND_PORT:-3230}"
DUMMY_APP="$GLIB_WEB_DIR/test/dummy-app"

if [[ -z "$GLIB_WEB_DIR" || ! -d "$DUMMY_APP" ]]; then
  echo "ERROR: dummy-app not found at '$DUMMY_APP'." >&2
  echo "       Set GLIB_WEB_DIR to your glib-web checkout, e.g.:" >&2
  echo "       GLIB_WEB_DIR=/path/to/glib-web scripts/cypress-local.sh" >&2
  exit 1
fi

echo "==> glib-web-npm : $NPM_DIR"
echo "==> glib-web     : $GLIB_WEB_DIR"
echo "==> backend port : $BACKEND_PORT"

# --- optional: check out a specific glib-web ref -----------------------------
# Resolve the ref like CI does: GLIB_WEB_REF env wins, else the committed
# .glib-web-ref file (per-branch pin), else leave the current checkout as-is.
GLIB_WEB_REF="${GLIB_WEB_REF:-}"
if [[ -z "$GLIB_WEB_REF" && -s "$NPM_DIR/.glib-web-ref" ]]; then
  GLIB_WEB_REF="$(tr -d '[:space:]' < "$NPM_DIR/.glib-web-ref")"
  echo "==> glib-web ref pinned by .glib-web-ref: $GLIB_WEB_REF"
fi
if [[ -n "$GLIB_WEB_REF" ]]; then
  if [[ ! -d "$GLIB_WEB_DIR/.git" ]]; then
    echo "ERROR: GLIB_WEB_REF set but '$GLIB_WEB_DIR' is not a git checkout." >&2
    exit 1
  fi
  # Refuse to switch branches over uncommitted work -- a checkout could stash
  # or clobber it silently.
  if [[ -n "$(git -C "$GLIB_WEB_DIR" status --porcelain)" ]]; then
    echo "ERROR: glib-web has uncommitted changes; refusing to switch to" >&2
    echo "       '$GLIB_WEB_REF'. Commit/stash them first, or unset GLIB_WEB_REF" >&2
    echo "       to test the current checkout as-is." >&2
    exit 1
  fi
  echo "==> Checking out glib-web ref: $GLIB_WEB_REF"
  git -C "$GLIB_WEB_DIR" fetch --quiet origin
  git -C "$GLIB_WEB_DIR" checkout --quiet "$GLIB_WEB_REF"
  # Fast-forward if it's a branch (no-op/harmless for a tag or detached sha).
  git -C "$GLIB_WEB_DIR" pull --quiet --ff-only origin "$GLIB_WEB_REF" 2>/dev/null || true
fi
echo "==> glib-web ref : $(git -C "$GLIB_WEB_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || echo '(not a git checkout)')"

# --- optional dependency setup ----------------------------------------------
if [[ "${SETUP:-}" == "1" ]]; then
  echo "==> Installing npm deps (glib-web-npm)"
  ( cd "$NPM_DIR" && yarn install )
  echo "==> Installing dummy-app deps (bundle + yarn link)"
  ( cd "$DUMMY_APP" && bundle install && yarn install )
  echo "==> Preparing dummy-app database"
  ( cd "$DUMMY_APP" && bundle exec rails db:prepare )
fi

# --- boot backend if not already up -----------------------------------------
SERVER_PID=""
STARTED_SERVER=0
LOG_FILE="$DUMMY_APP/log/cypress-local-server.log"

server_up() { curl -s -o /dev/null "http://localhost:$BACKEND_PORT"; }

cleanup() {
  if [[ "$STARTED_SERVER" == "1" && -n "$SERVER_PID" ]]; then
    echo "==> Stopping dummy-app (pgid $SERVER_PID)"
    # SERVER_PID is a setsid session/group leader, so its pid == pgid; signal
    # the whole group (negative pid) to reap puma and any children too.
    kill -TERM -"$SERVER_PID" 2>/dev/null || kill -TERM "$SERVER_PID" 2>/dev/null || true
    wait "$SERVER_PID" 2>/dev/null || true
    rm -f "$DUMMY_APP/tmp/pids/server.pid"
  fi
}
trap cleanup EXIT INT TERM

if server_up; then
  echo "==> Reusing server already running on port $BACKEND_PORT"
else
  echo "==> Booting dummy-app on port $BACKEND_PORT (log: $LOG_FILE)"
  # Run in a NEW process group (setsid) and exec into the server so the group
  # leader IS puma's parent chain -- lets cleanup kill the whole group and not
  # leak an orphaned puma when this pid differs from the listening process.
  # RAILS_ENV is pinned: shells that have run other tooling can carry an
  # ambient RAILS_ENV (e.g. `preview`) the dummy-app has no config for, which
  # kills the boot with a confusing database-config error. To use another env,
  # boot the server yourself -- the script reuses a running one.
  # setsid does not exist on macOS — fall back to a plain background job there
  # (cleanup already falls back to killing the single pid when the group kill
  # fails). Args are passed positionally to bash -c, not interpolated, so a
  # quote in the path can never become shell syntax.
  boot='cd "$1" && exec env RAILS_ENV=development bundle exec rails server -p "$2"'
  if command -v setsid >/dev/null; then
    setsid bash -c "$boot" _ "$DUMMY_APP" "$BACKEND_PORT" >"$LOG_FILE" 2>&1 &
  else
    bash -c "$boot" _ "$DUMMY_APP" "$BACKEND_PORT" >"$LOG_FILE" 2>&1 &
  fi
  SERVER_PID=$!
  STARTED_SERVER=1

  echo -n "==> Waiting for backend"
  for _ in $(seq 1 60); do
    if server_up; then echo " ready."; break; fi
    if ! kill -0 "$SERVER_PID" 2>/dev/null; then
      echo " FAILED (server exited)."; echo "--- last log lines ---"; tail -20 "$LOG_FILE"; exit 1
    fi
    echo -n "."; sleep 1
  done
  if ! server_up; then
    echo " TIMEOUT."; echo "--- last log lines ---"; tail -20 "$LOG_FILE"; exit 1
  fi
fi

# --- run cypress ------------------------------------------------------------
cd "$NPM_DIR"
CY_EXPOSE="BACKEND_PORT=$BACKEND_PORT"

# NOTE for sandboxed shells (AI agents, containers): NO browser can launch
# inside a seccomp/bwrap sandbox -- chrome and electron (even with
# --no-sandbox) both SIGSEGV at startup, verified 2026-08-13. Switching
# browsers does not help; this script must itself run OUTSIDE the sandbox
# (e.g. via a sandbox exclusion for its command line). See CONTRIBUTING.md
# "Running Cypress".

if [[ "${1:-}" == "open" ]]; then
  shift
  echo "==> Opening Cypress (interactive)"
  env -u ELECTRON_RUN_AS_NODE yarn cypress open --e2e --browser chrome --expose "$CY_EXPOSE" "$@"
else
  echo "==> Running Cypress (headless)"
  env -u ELECTRON_RUN_AS_NODE yarn cypress run --browser chrome --expose "$CY_EXPOSE" "$@"
fi
