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

cd "$(git rev-parse --show-toplevel)"

first_term='so''ul'
second_term='distill''ation'
pattern="(${first_term}|${second_term})"

tracked_source_files() {
  git ls-files |
    awk '
      index($0, "/migrations/") || index($0, "/tidb/migration_cleanup_test.go") || index($0, "/tidb/testdata/bootstrap_") { next }
      /\.(go|ts|tsx|js|mjs|cjs|json|md|ya?ml|sql)$/ { print; next }
      /(^|\/)(testdata|golden)(\/|$)/ { print }
    '
}

status=0

path_matches=$(
  git ls-files |
    awk 'index($0, "/migrations/") == 0 && index($0, "/tidb/migration_cleanup_test.go") == 0 && index($0, "/tidb/testdata/bootstrap_") == 0' |
    grep -Ein "$pattern" || true
)
if [[ -n "$path_matches" ]]; then
  printf '%s\n' "retired Role model vocabulary remains in tracked paths:" >&2
  printf '%s\n' "$path_matches" >&2
  status=1
fi

content_matches=$(
  tracked_source_files |
    while IFS= read -r file; do
      [[ -f "$file" ]] || continue
      grep -EinH "$pattern" "$file" || true
    done
)
if [[ -n "$content_matches" ]]; then
  printf '%s\n' "retired Role model vocabulary remains outside migrations:" >&2
  printf '%s\n' "$content_matches" >&2
  status=1
fi

exit "$status"
