#!/usr/bin/env bash
# Flyway validate using migration files from repo root; JDBC from env (staging / CI DB).
# Env: EMS_CI_FLYWAY_URL — if unset, skips (warn). Optional: EMS_CI_FLYWAY_USER, EMS_CI_FLYWAY_PASSWORD, FLYWAY_IMAGE
#
# CI notes:
# - Flyway runs in a throwaway container; without --network host, jdbc:…//localhost… hits the
#   container loopback, not the host (connection refused).
# - Some runners set missing secrets to the literal string "null"; passing FLYWAY_USER=null
#   overrides credentials embedded in the JDBC URL and yields "user 'null'" from the driver.
set -euo pipefail

if [[ -z "${EMS_CI_FLYWAY_URL:-}" ]]; then
  echo "WARN: EMS_CI_FLYWAY_URL not set — skipping remote Flyway validate (set Gitea secret for CI)."
  exit 0
fi

# Treat empty / JSON-null placeholders as unset so we do not override URL credentials.
_ci_sanitize_secret() {
  local v="${1-}"
  v="${v#"${v%%[![:space:]]*}"}"
  v="${v%"${v##*[![:space:]]}"}"
  case "${v,,}" in ''|'null'|'<null>') printf '%s' '' ;; *) printf '%s' "$v" ;; esac
}

EMS_CI_FLYWAY_USER="$(_ci_sanitize_secret "${EMS_CI_FLYWAY_USER-}")"
EMS_CI_FLYWAY_PASSWORD="$(_ci_sanitize_secret "${EMS_CI_FLYWAY_PASSWORD-}")"

ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
cd "$ROOT"

IMG="${FLYWAY_IMAGE:-flyway/flyway:12}"

# POZOR: žádné -v bind mounty! Docker CLI mluví s HOSTOVSKÝM daemonem; když job
# běží v kontejneru (container mód runneru), cesty checkoutu na hostu neexistují
# a flyway dostane prázdné adresáře ("applied migration not resolved locally").
# docker cp streamuje soubory od klienta → funguje v host i container módu.
# /sql (ne /flyway/sql): image deklaruje /flyway/sql jako VOLUME — anonymní volume
# by při startu zastínil soubory nakopírované přes docker cp do vrstvy kontejneru.
args=(
  create
  --network host
  -e "FLYWAY_URL=${EMS_CI_FLYWAY_URL}"
  -e "FLYWAY_SCHEMAS=ems"
  -e "FLYWAY_LOCATIONS=filesystem:/sql/migration,filesystem:/sql/routines,filesystem:/sql/views"
  # Změněná/nová repeatable je proti DB "pending" — to není chyba (aplikuje ji
  # deploy migrate). Immutabilitu VERZOVANÝCH hlídá ci_check_migration_immutability.sh.
  -e "FLYWAY_IGNORE_MIGRATION_PATTERNS=*:pending"
)

if [[ -n "$EMS_CI_FLYWAY_USER" ]]; then
  args+=(-e "FLYWAY_USER=${EMS_CI_FLYWAY_USER}")
fi
if [[ -n "$EMS_CI_FLYWAY_PASSWORD" ]]; then
  args+=(-e "FLYWAY_PASSWORD=${EMS_CI_FLYWAY_PASSWORD}")
fi

args+=("$IMG" validate)

echo "Running Flyway validate against remote DB (schema ems)…"
cid="$(docker "${args[@]}")"
cleanup() { docker rm -f "$cid" >/dev/null 2>&1 || true; }
trap cleanup EXIT

docker cp "$ROOT/db" "$cid:/sql"

docker start "$cid" >/dev/null
rc="$(docker wait "$cid")"
docker logs "$cid"
exit "$rc"
