#!/usr/bin/env bash
# One-time scrub of residual ScadaLink/scadalink references → ScadaBridge.
# Operates on git-tracked TEXT files only (git grep -I skips binaries),
# minus carve-out migration records whose before→after meaning must survive.
# Substitutions are applied most-specific-first so a broad rule cannot
# double-replace an earlier result. Idempotent: re-running is a no-op.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

# NOTE: this script only sees git-TRACKED files (via git grep). Git-ignored
# trees — notably /deploy/ (see .gitignore) — are out of its reach and were
# scrubbed separately, by hand, with the same substitution set. A git-based
# completeness gate likewise cannot see them; verify those trees with a plain
# `grep -rniI scadalink <dir>`.

# Carve-outs (migration records): prior rename tooling/design, the DB-rename
# helper, this script itself, and the rename design + plan docs (which document
# the old→new mapping and would be self-corrupted by the substitution).
EXCLUDES_RE='^(tools/rename-to-scadabridge\.sh|tools/scrub-scadalink-refs\.sh|docker/rename-databases\.sh|docs/plans/2026-05-28-scadabridge-rename-design\.md|docs/plans/2026-05-31-folder-repo-rename-scadabridge-design\.md|docs/plans/2026-05-31-folder-repo-rename-scadabridge-plan\.md)$'

files=()
while IFS= read -r f; do
  [[ "$f" =~ $EXCLUDES_RE ]] && continue
  files+=("$f")
done < <(git grep -liI 'scadalink' -- .)

if [[ ${#files[@]} -eq 0 ]]; then
  echo "No files to scrub."
  exit 0
fi

printf 'Scrubbing %d file(s):\n' "${#files[@]}"
printf '  %s\n' "${files[@]}"

sed -i '' \
  -e 's/ScadaLink\.Host\.exe/ZB.MOM.WW.ScadaBridge.Host.exe/g' \
  -e 's/ScadaLink__/ScadaBridge__/g' \
  -e 's/SCADALINK_/SCADABRIDGE_/g' \
  -e 's/scadaLinkVersion/scadaBridgeVersion/g' \
  -e 's/scadalink_app/scadabridge_app/g' \
  -e 's/ScadaLink/ScadaBridge/g' \
  -e 's/scadalink/scadabridge/g' \
  "${files[@]}"

echo "Done."
