#!/usr/bin/perl

use Getopt::Long;

GetOptions("list|l=s"    => \$list,
	   "pset|p=s"    => \$pset);

if ($list) {
	$dir = `dirname $list`;
	chomp $dir;
	open (LIST, $list) || die "Can't open listfile $list";
	while ($patch = <LIST>) {
		chomp $patch;
		$patch =~ s/#.*//;		# strip comments
		$patch =~ s/\s.*//;		# strip any trailing space, etc
		next if ($patch eq "");		# it's blank, Jim!
		if ($patch !~ m#/#) {		# no / - assume it's unqualified
			$patch = "$dir/$patch";
		}
		push @patches, $patch;
	}
} else {
	@patches = @ARGV;
}

print join("\n",@patches) . "\n";

if ($pset) {
	$pset =~ /(\d+),(\d+)/;
	$pset_num = $1;
	$pset_inc = $2;
	print "$pset | $pset_num | $pset_inc\n";
	print "pset application starting $pset_num, increments of $pset_inc\n";
}

foreach $patch (@patches) {
	die "No such patch: $patch" unless (-f $patch);
	if ($pset_num) {
		$pset_name = $patch;
		$pset_name =~ s#.*/##;
		$pset_name =~ s/\.patch$//;
		$pset_name =~ s/-/_/g;
		$pset_name = $pset_num . "-" . $pset_name;
		print "Applying $patch as $pset_name\n";
		print "pset add $pset_name $patch\n";
		$failed = system ("pset add $pset_name $patch");
		$pset_num += $pset_inc;
	} else {
		print"Applying $patch ...\n";
		$failed = system ("patch -p1 < $patch");
	}
	if ($failed != 0) {
		print "Failed patch: $?: $patch\n";
		last;
	}
}