#! /usr/bin/perl -w
#
# Kernel patch applicator
#
# (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 -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;
}

# make sure debian-patches directory exists
mkdir "debian-patches", 0755;

# 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;

# apply patches
foreach (@patchlist) {
	($patchname, $patchhostarch) = split;

	# always apply unless otherwise specified
	$patchhostarch = "all" if ($patchhostarch eq "");

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

	# skip if patch not for this host arch
	if (($patchhostarch ne "all"    )
	&&  ($patchhostarch ne $hostarch))
	{
		print "not required for $hostarch host.\n";
		next;
	}

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

	if (system("zcat $patchdir/patches/$patchname.diff.gz | patch $patch_opts >$sentinal")) {
		print "FAILED.\n";
	}
	else {
		print "applied.\n";
	}
}
