#!/usr/bin/env bash
# Apply patches/<repo-path>/*.patch to a synced tree. Idempotent: a patch that
# already reverse-applies cleanly is skipped; one that neither applies nor is
# already in fails the run loudly (an upstream sync moved its anchor).
# Every applied patch is recorded under $SRC/.vanta-applied/, so a revised patch
# is swapped in over the old version (reverse the record, apply the new one)
# instead of reading as a moved anchor.
# Usage: tools/patches.sh [source-root]
set -uo pipefail
P=$(cd "$(dirname "$0")/.." && pwd)
SRC=${1:-$HOME/vanta}
REC=$SRC/.vanta-applied
rc=0
record() { mkdir -p "$REC/$repo" && cp "$patch" "$REC/$repo/$name"; }
while IFS= read -r patch; do
  rel=${patch#"$P/patches/"}
  repo=$(dirname "$rel")
  name=$(basename "$patch")
  old=$REC/$repo/$name
  if git -C "$SRC/$repo" apply -R --check "$patch" 2>/dev/null; then
    echo "have  $repo $name"; record
  elif git -C "$SRC/$repo" apply --check "$patch" 2>/dev/null; then
    git -C "$SRC/$repo" apply "$patch" && echo "apply $repo $name" && record
  elif [ -f "$old" ] && ! cmp -s "$old" "$patch" && git -C "$SRC/$repo" apply -R --check "$old" 2>/dev/null \
      && git -C "$SRC/$repo" apply -R "$old" && git -C "$SRC/$repo" apply --check "$patch" 2>/dev/null; then
    git -C "$SRC/$repo" apply "$patch" && echo "swap  $repo $name (revised)" && record
  else
    echo "FAIL  $repo $name (anchor moved; re-author against the synced tree)"
    rc=1
  fi
done < <(find "$P/patches" -name '*.patch' | sort)
exit $rc
