#! /usr/bin/perl -w
#
# Kernel patch remover
#
# (C) 2000 Nick Holgate <holgate@debian.org>
#

$patchver   = "2.2.17";
$arch       = "m68k";
$hostarch   = `dpkg-architecture -qDEB_HOST_ARCH`;
$patchdir   = "/usr/src/kernel-patches/$arch/$patchver";
$patch_opts = "-l -s -p1";

if ( ! -d "kernel" || ! -d "Documentation" ) {
	print STDERR "Not in kernel top level directory. Exiting\n";
	exit 1;
}

# get rid of newline
chomp $hostarch;

# Get kernel version from Makefile
open MF, "Makefile";
while (<MF>) {
	if    ( /^VERSION\D+(\d+)/    ) { $ver = $1; }
	elsif ( /^PATCHLEVEL\D+(\d+)/ ) { $pch = $1; }
	elsif ( /^SUBLEVEL\D+(\d+)/   ) { $sub = $1; }
}
close MF;
$kernelver = "$ver.$pch.$sub";

if ( $kernelver ne $patchver ) {
	print STDERR "Wrong kernel source version for this patch set.\n";
	exit 1;
}

# read patchlist
open PL, "$patchdir/patch-list";
$maxnamelen  = 0;
while (<PL>) {
	chomp;
	s/\#.*//g; 			# strip comments
	next if /^\s*$/;	# skip blank lines
	push @patchlist, $_;

	($patchname) = split;
	$namelen     = length $patchname;
	$maxnamelen  = $namelen if ($namelen > $maxnamelen);
}
close PL;

# unbuffered output
$| = 1;

# remove patches in reverse order
foreach (reverse @patchlist) {
	($patchname) = split;

	print "Patch $patchname ..." . "." x ($maxnamelen - length $patchname) . " ";

	$sentinal = "debian-patches/APPLIED_${arch}_$patchname";
	if ( ! -f $sentinal ) {
		print "not applied.\n";
		next;
	}

	system("zcat $patchdir/patches/$patchname.diff.gz | patch -R $patch_opts\n");
	unlink $sentinal;
	print "removed.\n";
}

# remove debian-patches directory if empty
rmdir "debian-patches";

