#! /usr/bin/perl -w
use strict;
no strict 'refs';

# This "unpatch" script was automatically generated by
# dh_installkpatches from unpatch.tmpl $Revision: 1.17.1.4.1.23 $

die "not in kernel top level directory"
  unless -d 'kernel' and -d 'Documentation';

our $ARCHITECTURE=`dpkg --print-installation-architecture`;
our $PATCHID='kdbcore';
our $PATCHARCH='all';

our $TOPPATCHDIR='/usr/src/kernel-patches';
our $DECOMPRESSOR='zcat -f';

our $STAMP="debian/APPLIED_${PATCHARCH}_$PATCHID";

our $PATCH_OPTIONS='--ignore-whitespace --silent';

-f $STAMP or exit 0;

die <<EOF
ERROR: "Kernel debugger architecture-independant core" patch was applied using old mechanism.
The relevant patch file may even not be on your system any more.
I strongly suggest you remove this kernel tree and unpack a clean one.
EOF
unless -s $STAMP;
open STAMP, $STAMP;
our ($PATCHFILE,$STRIPLEVEL,@DEPENDS);
if ( `wc -l < $STAMP` != 1 ) {
  my $DEPENDS;
  while (<STAMP>) {
    m/^(\w+)='(.*)'$/ or die "parse error reading $STAMP";
    $$1 = $2;
  }
  @DEPENDS = split /\s+/, $DEPENDS;
} else {
  # old format
  my $APPLY_INFO=<STAMP>;
  ($PATCHFILE,$STRIPLEVEL) = split /\#/, ${APPLY_INFO};
}
close STAMP;
die <<EOF
ERROR: applied "Kernel debugger architecture-independant core" patch file could not be found.
Presumably the package containing it was removed or upgraded.
I strongly suggest you remove this kernel tree and unpack a clean one.
EOF
  unless -r $PATCHFILE;
if (system ('grep -l "^DEPENDS=.*[\' ]all/unpatch/kdbcore[\' ]" debian/APPLIED_* >/dev/null 2>/dev/null')
    == 0) {
  # There are patches depending on this one, to be removed before.
  # the dep will be removed by the last of those other patches.
  print STDERR "NOT unpatching \"Kernel debugger architecture-independant core\" since other patches still rely on it\n";
  exit 0;
}

print STDERR "START unpatching patch \"Kernel debugger architecture-independant core\"\n";

system ("$DECOMPRESSOR $PATCHFILE | patch -R -p$STRIPLEVEL $PATCH_OPTIONS") == 0
  or die "unpatching failed";
unlink "debian/APPLIED_${PATCHARCH}_$PATCHID"
  if -e "debian/APPLIED_${PATCHARCH}_$PATCHID";
unlink "debian/image.d/register-kdbcore"
  if -e "debian/image.d/register-kdbcore";

if (@DEPENDS > 0) {
  print STDERR 'Also un-applying the following patches: ' . join ' ', @DEPENDS;
  for my $dep (@DEPENDS) {
    die "Could not unpatch dependency: $dep - stopping here."
      unless -x "${TOPPATCHDIR}/$dep";
    system ("${TOPPATCHDIR}/$dep") == 0
      or die "error unpatching $dep";
  }
}
print STDERR "Removing empty files:\n";
# make an exception for ./debian, or else the stamp files will go too.
system ('find . -path ./debian -prune -o ' .
        '-type f -size 0 ! -name "APPLIED*" -exec rm {} \; -print');
print STDERR "Done.\n";
rmdir "debian/image.d" if -d "debian/image.d";
rmdir "debian" if -d "debian";

print STDERR "END unpatching patch \"Kernel debugger architecture-independant core\"\n";
