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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

BASE_URL="${LINEUP_BASE_URL:-https://lineupfrance.com}"
WITH_TESTS=1

usage() {
  cat <<'EOF'
Usage:
  ./scripts/release_prod_v1.sh [--url <base_url>] [--skip-tests]

Examples:
  ./scripts/release_prod_v1.sh --url https://lineupfrance.com
  ./scripts/release_prod_v1.sh --url https://lineupfrance.com --skip-tests
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --url)
      BASE_URL="${2:-}"
      shift 2
      ;;
    --skip-tests)
      WITH_TESTS=0
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1"
      usage
      exit 1
      ;;
  esac
done

if [[ -z "$BASE_URL" ]]; then
  echo "ERROR: --url cannot be empty."
  exit 1
fi

echo "== LineUp release prod v1 =="
echo "Root: $ROOT_DIR"
echo "URL: $BASE_URL"
echo

if [[ ! -x "./scripts/deploy_release_cpanel.sh" ]]; then
  echo "ERROR: ./scripts/deploy_release_cpanel.sh missing or not executable."
  exit 2
fi

if [[ ! -x "./scripts/go_live_v1.sh" ]]; then
  echo "ERROR: ./scripts/go_live_v1.sh missing or not executable."
  exit 2
fi

if [[ ! -L "$HOME/public_html" ]]; then
  echo "WARN: ~/public_html is not a symlink."
  echo "Ensure cPanel docroot points to current/public before continuing."
fi

echo "-- Deploying release --"
LINEUP_SMOKE_URL="$BASE_URL" ./scripts/deploy_release_cpanel.sh

echo
echo "-- Running go-live checks on current release --"
cd "$HOME/current"
if [[ "$WITH_TESTS" -eq 1 ]]; then
  ./scripts/go_live_v1.sh --url "$BASE_URL" --with-tests
else
  ./scripts/go_live_v1.sh --url "$BASE_URL"
fi

echo
echo "Release prod V1: OK"
echo "If needed, rollback command:"
echo "  cd ~/current && ./scripts/rollback_release_cpanel.sh"
