#!/usr/bin/perl

opendir (CURRENTDIR, '.') || die;
@files = sort (grep /^\d/, (grep !/^\.\.?$/, readdir CURRENTDIR));
closedir (CURRENTDIR);

$last = pop (@files);
print "Starting from $last ...\n";

while ($patch = shift(@ARGV)) {
	die "No such patch: $patch" unless (-f $patch);
	$new = $patch;
	$new =~ s/.*\///;
	print"... $new $patch\n";
	dupview($last, $new);
	$failed = system ("(cd $new; patch -p1) < $patch");
	if ($failed != 0) {
		print "Failed patch: $?\n";
		last;
	}
	$last = $new;
}

sub dupview
{
	my ($oldview, $newview) = @_;

	die "no old view: $oldview" if (!-d $oldview);
	die "existing new view: $newview" if (-d $newview);
	system ("cp -lR $oldview $newview");
	system ("find $newview -type f | xargs chmod ugo-w");
	system ("find $newview -type d | xargs chmod u+w");
}

