#!/usr/bin/env bash
#
# Fail if an already-committed Flyway migration was modified or deleted.
#
# Flyway checksums every migration it applies and refuses to start when the file
# later changes ("Migration checksum mismatch for migration version N"). That
# check runs before the EntityManager is built, so the whole application fails to
# boot - not one endpoint, everything. That is exactly how production went down
# on 2026-07-31 after V48 was edited post-deploy.
#
# Adding a new V{n+1} file is always fine. Changing an existing one never is.
#
# Usage:
#   deploy/check-migrations.sh [BASE_REF]
#
# BASE_REF defaults to the previous commit. CI should pass the last successfully
# deployed commit so a push containing several commits is checked as a whole.
#
# Exit codes: 0 = clean, 1 = a migration was modified/deleted.

set -euo pipefail

MIGRATION_DIR="ordrat-infrastructure/src/main/resources/db/migration"
BASE_REF="${1:-HEAD~1}"

if ! git rev-parse --verify --quiet "${BASE_REF}" >/dev/null; then
    echo "check-migrations: base ref '${BASE_REF}' not found - skipping (first build?)."
    exit 0
fi

# --diff-filter=MD: only Modified and Deleted. Added files are fine; a rename
# shows up as a delete of the old name, which we do want to catch.
violations="$(git diff --name-status --diff-filter=MD "${BASE_REF}" HEAD -- "${MIGRATION_DIR}" || true)"

if [ -z "${violations}" ]; then
    echo "check-migrations: OK - no existing migration was modified since ${BASE_REF}."
    exit 0
fi

cat >&2 <<EOF

  ────────────────────────────────────────────────────────────────────────────
  BUILD BLOCKED: an already-committed migration was changed.

$(echo "${violations}" | sed 's|^|      |')

  Flyway has already applied these files in every environment that ran them and
  stored their checksums. Shipping a changed file makes the application fail to
  start with "Migration checksum mismatch", taking the whole API down.

  Fix: restore the file to its committed content and put your change in a NEW
  migration:

      git checkout ${BASE_REF} -- ${MIGRATION_DIR}
      # then add ${MIGRATION_DIR}/V<next>__your_change.sql

  Only if a deployed environment is ALREADY broken by such an edit, realign the
  stored checksum to the current file and let a new migration carry the data fix:

      UPDATE flyway_schema_history SET checksum = <resolved-locally-value>
       WHERE version = '<n>';
  ────────────────────────────────────────────────────────────────────────────

EOF
exit 1
