#!/usr/bin/perl

##
## mk-link-initrd.pl
## 
## Create links in /boot for the linux kernel and ramdisk
##
## Pierre Allix aka Kototama <kototama-code(at)altern.org>
##
use Getopt::Long;
use File::stat;

sub show_usage {
  print "Usage : $0 [OPTIONS] kernel-image [old-kernel-image]\n";
  print "\nCreate links in /boot for the linux kernel and ramdisk";
  print "\nOptions:\n";
  print "--verbose\n";
  print "--no-actions\n";
  exit 0;
}

my $verbose = 0;
my $no_actions = 0;
my $help = 0;

my $version;
my $oldversion = "";

my $boot = "./boot/";
my $vmlinuz = "vmlinuz";
my $initrd = "initrd.img";
my $vmlinuzold = "vmlinuz.old";
my $initrdold = "initrd.img.old";

my $createold = 1;

$result = GetOptions("verbose" => \$verbose,
		     "no-actions" => \$no_actions,
		    "help" => \$help);

if($help or @ARGV < 1) { show_usage(); }

if($ARGV[0] =~ /.*?(-.+)/) {
  $version = $1;
} else { die "Argument $ARGV[0] invalide\n"; }

chdir($boot);

if(defined($ARGV[1])) {
  if($ARGV[1] =~ /.*?(-.+)/) {
    $oldversion = $1;
  } else { die "Argument $ARGV[1] invalide\n"; }
} else {  
  
   $old = readlink($vmlinuz);
   if ($old eq "") { $createold = 0; }
   ($oldversion) = $old =~ /.*?(-.+)/;
}

if ( -x $vmlinuz && not -l $vmlinuz) {
  print "Creating ${boot}$vmlinuz [ ERROR  ]\n";
} else {
  unlink($vmlinuz);
  if(not $no_actions) { symlink($vmlinuz.$version, $vmlinuz); }
  print "Creating ${boot}$vmlinuz [  OK  ]\n";
}

if ( -x $initrd && not -l $initrd) {
  print "Creating ${boot}$initrd [  ERROR  ]\n";
} else {
  unlink($initrd);
  if(not $no_actions) { symlink($initrd.$version, $initrd); }
  print "Creating ${initrd}$version [  OK  ]\n";
}

if ( $createold ) {
unlink($vmlinuzold);
if(not $no_actions) { symlink($vmlinuz.$oldversion, $vmlinuzold); }
print "Creating ${boot}$vmlinuzold [  OK  ]\n";
unlink($initrdold);
if(not $no_actions) { symlink($initrd.$oldversion, $initrdold); }
print "Creating ${boot}$initrdold  [ OK  ]\n";
}






