#! /usr/bin/perl
#
use strict;
use warnings;
use POSIX ();

$|=1;

# Predefined values:
my $version         = "@abiname@@localversion@";
my $kimage          = "@image-stem@";
my $preinst_hook    = '';       #Normally we do not
my $package_name    = "linux-image-$version";

#known variables
my $realimageloc    = "/boot/";
my $CONF_LOC        = '/etc/kernel-img.conf';

my $modules_base    = '/lib/modules';

die "Pre inst Internal error. Aborting." unless $version;

exit 0 if $ARGV[0] =~ /abort-upgrade/;
exit 1 unless $ARGV[0] =~ /(install|upgrade)/;

if (-r "$CONF_LOC" && -f "$CONF_LOC"  ) {
  if (open(CONF, "$CONF_LOC")) {
    while (<CONF>) {
      chomp;
      s/\#.*$//g;
      next if /^\s*$/;

      $preinst_hook    = "$1"  if /preinst_hook\s*=\s*(\S+)/i;
    }
    close CONF;
  }
}

# set the env var stem
$ENV{'STEM'} = "linux";

sub system_failure_message {
  if ($? < 0) {
    return "$!";
  } elsif (POSIX::WIFSIGNALED($?)) {
    return sprintf('signal %d', POSIX::WTERMSIG($?));
  } else {
    return sprintf('exit code %d', POSIX::WEXITSTATUS($?));
  }
}

sub run_hook {
  my $type   = shift;
  my $script = shift;

  print STDERR "Running $script.\n";
  if (system ("$script $version $realimageloc$kimage-$version")) {
    die ("$script failed: " . system_failure_message());
  }
}

my $options;
for (@ARGV) {
	s,','\\'',g;
	$options .= " '$_'";
}
$ENV{'DEB_MAINT_PARAMS'}="$options";

## Run user hook script here, if any
if (-x "$preinst_hook") {
  &run_hook("preinst", $preinst_hook);
}
if (-d "/etc/kernel/preinst.d") {
  system ("run-parts --report --exit-on-error --arg=$version" .
          " --arg=$realimageloc$kimage-$version" .
          " /etc/kernel/preinst.d") &&
            die "Failed to process /etc/kernel/preinst.d";
}

exit 0;

__END__
