#!/usr/bin/env bash
# Apply the whole patch series, in order, to a fresh sparse clone of each
# patched LineageOS lineage-24.0 repo: the exact step apply.sh runs on the box.
# Only the directories the patches touch are checked out (blobless), so this
# runs on Zo in a minute. Usage: tools/patchcheck.sh   (exit 1 = a patch moved)
set -euo pipefail
P=$(cd "$(dirname "$0")/.." && pwd)
W=${PATCHCHECK_DIR:-$P/build/patchcheck}
declare -A REPO=( [frameworks/base]=LineageOS/android_frameworks_base [bootable/recovery]=LineageOS/android_bootable_recovery )
rc=0
for rel in $(cd "$P/patches" && find . -name '*.patch' -exec dirname {} \; | sed 's|^\./||' | sort -u); do
  url=${REPO[$rel]:-}
  [ -n "$url" ] || { echo "FAIL  no upstream known for $rel (add it to REPO in tools/patchcheck.sh)"; rc=1; continue; }
  d="$W/$rel"
  rm -rf "$d"; mkdir -p "$(dirname "$d")"
  git clone -q --depth 1 --filter=blob:none --sparse -b lineage-24.0 "https://github.com/$url" "$d"
  # A file in a subdirectory brings its whole directory; a top-level file is named exactly.
  pats=$(grep -h '^+++ b/' "$P/patches/$rel"/*.patch | sed 's|^+++ b/||' \
         | awk -F/ 'NF > 1 { sub("/[^/]*$", "/*"); print; next } { print "/" $0 }' | sort -u)
  # shellcheck disable=SC2086
  git -C "$d" sparse-checkout set --no-cone $pats >/dev/null
  for p in "$P/patches/$rel"/*.patch; do
    if git -C "$d" apply "$p"; then echo "ok    $rel $(basename "$p")"; else echo "FAIL  $rel $(basename "$p")"; rc=1; fi
  done
done
exit $rc
