#!/usr/bin/perl -w
#
# This unpatches all the patches in a series file
#

open(IN,"patches/series") || die "can't open patches/series\n";

my @patches;

while(<IN>) {
	chomp;
	next if (/^\s*(#.*)?$/);
	if (/^\s*(.*[^\s])\s*$/) {
		my $patch = $1;
		$patches[$#patches+1] = $patch;
	}
}

for (my $i=$#patches; $i >= 0; $i--) {
	`patch --dry-run -R -p1 -ts < patches/$patches[$i]`;
	print "unpatching $patches[$i]\n";
	if ($?) {
		system("patch --dry-run -R -p1 -t < patches/$patches[$i]");
		print "$patches[$i] failed!\n";
		exit(-1);
	} else {
		`patch -R -p1 -ts < patches/$patches[$i]`;
	}
}
