patch_dir = /usr/src/toolchain/patches/gdb/

debian_patches := $(basename $(shell cd $(patch_dir) && ls *.patch | grep -v rules.patch))

patched-%: $(patch_dir)/%.patch
	patch -p1 < $< > log-$@ 2>&1
	echo "$* patch applied." >> $@

apply-patches: patched-stamp

patched-stamp: $(foreach p,$(debian_patches),patched-$(p))
	touch patched-stamp

reverse-patches:
	for stamp in patched-*; do \
	  case "$$stamp" in patched-stamp|patched-\*) continue; esac; \
	  patch=`echo $$stamp | sed -e 's/patched-//'`; \
	  echo "trying to revert patch $$patch ..."; \
	  if patch -p1 -R -E < $(patch_dir)/$$patch.patch; then \
	    echo "reverted $$patch patch."; \
	    rm -f $$stamp log-$$stamp; \
	  else \
	    echo "error in reverting $$patch patch."; \
	    exit 1; \
	  fi; \
	done
	rm -f patched-stamp
