#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"
FIXTURE_PORT="${FIXTURE_PORT:-8092}"
BASE_URL="${E2E_BASE_URL:-http://127.0.0.1:${FIXTURE_PORT}}"
ENV_FILE="${ROOT_DIR}/credentials/.env"

load_env_value() {
  local key="$1"
  local line
  line="$(grep -E "^${key}=" "${ENV_FILE}" | tail -n 1 || true)"
  line="${line#*=}"
  line="${line%\"}"
  line="${line#\"}"
  line="${line%\'}"
  line="${line#\'}"
  printf '%s' "${line}"
}

cd "${ROOT_DIR}"

if [[ -f "${ENV_FILE}" ]]; then
  E2E_REMOTE_ADMIN="${E2E_REMOTE_ADMIN:-$(load_env_value E2E_REMOTE_ADMIN)}"
  E2E_REMOTE_ADMIN_BASE_URL="${E2E_REMOTE_ADMIN_BASE_URL:-$(load_env_value E2E_REMOTE_ADMIN_BASE_URL)}"
  E2E_REMOTE_ADMIN_USER="${E2E_REMOTE_ADMIN_USER:-$(load_env_value E2E_REMOTE_ADMIN_USER)}"
  E2E_REMOTE_ADMIN_PASS="${E2E_REMOTE_ADMIN_PASS:-$(load_env_value E2E_REMOTE_ADMIN_PASS)}"
  export E2E_REMOTE_ADMIN E2E_REMOTE_ADMIN_BASE_URL E2E_REMOTE_ADMIN_USER E2E_REMOTE_ADMIN_PASS
fi

if [[ "${E2E_REMOTE_ADMIN:-0}" = "1" && -n "${E2E_REMOTE_ADMIN_BASE_URL:-}" && -z "${E2E_BASE_URL:-}" ]]; then
  BASE_URL="${E2E_REMOTE_ADMIN_BASE_URL}"
fi

if [[ "${E2E_REMOTE_ADMIN:-0}" != "1" ]]; then
  FIXTURE_PORT="${FIXTURE_PORT}" scripts/run_fixture_server.sh start >/dev/null
fi

if [[ ! -d node_modules ]]; then
  npm install
fi

npx playwright install chromium
E2E_BASE_URL="${BASE_URL}" npx playwright test
