#!/usr/bin/perl

$PATCHDIR="/usr/src/kernel-patches/i386/2.2.17";
$STAMP="APPLIED_i386_2.2.17_kernel-patch-2.2.17-pc9800";
%patches =
( 
 'linux98-2.2.17.diffs.gz', 'zcat',
);

$| = 1;

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

if ( -e $STAMP ) {
    exit 0; 
}

# First, check whether all the files can apply successfully.
$apply="yes";
foreach $p (keys %patches) {
    printf STDERR "checking whether $p works... ";
    if (system("$patches{$p} $PATCHDIR/$p | patch --dry-run -s -p1 > /dev/null")) {
	$apply="no";
	printf STDERR "no\n";
    } else {
	printf STDERR "yes\n";
    }
}

#Then apply if apply = yes or -f option is specified.
if (( $apply eq "yes" ) || ( $ARGV[0] eq "-f" )) {
    foreach $p (keys %patches) {
	printf STDERR "patching $p... ";
	system("$patches{$p} $PATCHDIR/$p | patch -E -p1 >> $STAMP");
	printf STDERR "done.\n";
    }
}
