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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CLIENT_APP_DIR="${CLIENT_APP_DIR:-/Users/gsent/Documents/untitled2/apps/client_app}"
LINER_APP_DIR="${LINER_APP_DIR:-/Users/gsent/Documents/untitled2/apps/liner_app}"
BASE_URL="${BASE_URL:-http://127.0.0.1:8000}"
API_BASE_URL="${API_BASE_URL:-$BASE_URL/api}"
TIMEOUT_SECONDS="${TIMEOUT_SECONDS:-60}"
RUN_BO_E2E="${RUN_BO_E2E:-1}"
RUN_CLIENT_REAL_E2E="${RUN_CLIENT_REAL_E2E:-1}"
RUN_LINER_REAL_E2E="${RUN_LINER_REAL_E2E:-1}"

: "${CLIENT_LOGIN:=client@lineup.fr}"
: "${CLIENT_PASSWORD:=Lineup12j}"
: "${LINER1_LOGIN:=liner@lineup.fr}"
: "${LINER1_PASSWORD:=Lineup12j}"
: "${LINER2_LOGIN:=liner2@lineup.fr}"
: "${LINER2_PASSWORD:=Lineup12j}"

printf '== LineUp local validation suite ==\n'
printf 'BO root: %s\n' "$ROOT_DIR"
printf 'Client app: %s\n' "$CLIENT_APP_DIR"
printf 'Liner app: %s\n' "$LINER_APP_DIR"
printf 'Base URL: %s\n\n' "$BASE_URL"

if [[ ! -x "$ROOT_DIR/scripts/e2e_local_lineup.sh" ]]; then
  echo "Missing executable: $ROOT_DIR/scripts/e2e_local_lineup.sh" >&2
  exit 1
fi

if [[ ! -x "$CLIENT_APP_DIR/scripts/e2e_real_client_api.sh" ]]; then
  echo "Missing executable: $CLIENT_APP_DIR/scripts/e2e_real_client_api.sh" >&2
  exit 1
fi

if [[ ! -x "$LINER_APP_DIR/scripts/e2e_real_liner_api.sh" ]]; then
  echo "Missing executable: $LINER_APP_DIR/scripts/e2e_real_liner_api.sh" >&2
  exit 1
fi

if [[ "$RUN_BO_E2E" == "1" ]]; then
  printf '%s\n' '-- BO real local E2E --'
  BASE_URL="$BASE_URL" \
  TIMEOUT_SECONDS="$TIMEOUT_SECONDS" \
  CLIENT_LOGIN="$CLIENT_LOGIN" \
  CLIENT_PASSWORD="$CLIENT_PASSWORD" \
  LINER1_LOGIN="$LINER1_LOGIN" \
  LINER1_PASSWORD="$LINER1_PASSWORD" \
  LINER2_LOGIN="$LINER2_LOGIN" \
  LINER2_PASSWORD="$LINER2_PASSWORD" \
  "$ROOT_DIR/scripts/e2e_local_lineup.sh"
  printf '\n'
fi

if [[ "$RUN_CLIENT_REAL_E2E" == "1" ]]; then
  printf '%s\n' '-- client_app real API E2E --'
  BASE_URL="$API_BASE_URL" \
  CLIENT_LOGIN="$CLIENT_LOGIN" \
  CLIENT_PASSWORD="$CLIENT_PASSWORD" \
  LINER1_LOGIN="$LINER1_LOGIN" \
  LINER1_PASSWORD="$LINER1_PASSWORD" \
  LINER2_LOGIN="$LINER2_LOGIN" \
  LINER2_PASSWORD="$LINER2_PASSWORD" \
  "$CLIENT_APP_DIR/scripts/e2e_real_client_api.sh"
  printf '\n'
fi

if [[ "$RUN_LINER_REAL_E2E" == "1" ]]; then
  printf '%s\n' '-- liner_app real API E2E --'
  BASE_URL="$API_BASE_URL" \
  BACKEND_ROOT="$ROOT_DIR" \
  CLIENT_LOGIN="$CLIENT_LOGIN" \
  CLIENT_PASSWORD="$CLIENT_PASSWORD" \
  LINER_LOGIN="$LINER1_LOGIN" \
  LINER_PASSWORD="$LINER1_PASSWORD" \
  "$LINER_APP_DIR/scripts/e2e_real_liner_api.sh"
  printf '\n'
fi

printf 'Suite complete: OK\n'
