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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PATCHDIR="${ROOT}/patches"

usage() {
  cat <<USAGE
Usage: $0
Applies patches 0001–0004 to the working tree (idempotent).
USAGE
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

cd "$ROOT"

if [[ ! -d "$PATCHDIR" ]]; then
  echo "ERROR: patches/ directory not found at: $PATCHDIR" >&2
  exit 1
fi

shopt -s nullglob
patches=( "$PATCHDIR"/000[1-4]-*.patch )

if (( ${#patches[@]} == 0 )); then
  echo "ERROR: no 0001–0004 patches found in $PATCHDIR" >&2
  exit 1
fi

for p in "${patches[@]}"; do
  echo "==> Checking $(basename "$p")"
  if patch --dry-run -p1 < "$p" >/dev/null 2>&1; then
    echo "==> Applying $(basename "$p")"
    patch -p1 < "$p"
  else
    echo "==> Skipping $(basename "$p") (already applied or does not apply cleanly)"
  fi
done

echo "Done."
