#!/usr/bin/perl

# this script takes command kernel rpms (either installed rpms or rpm files)
# and create various files in all_kernels/:
#     all.kernels/VER/all_modules.tar  (used for all.rdz)
#     all.kernels/VER/modules.dep
#     all.kernels/VER/modules.alias
#     all.kernels/VER/vmlinuz

use lib '../kernel';
use MDK::Common;
use list_modules;

(my $karch = arch()) =~ s/^i.86$/i586/;
my $rpm = 'rpm --nosignature';


@ARGV or die "usage: ./update_kernel <installed kernel name> ...\n";

eval { rm_rf('all.kernels') }; #- remove old things
mkdir 'all.kernels';

my @kernels = map {
    my $kern_ver = rpm2version($_);
	extract_installed_rpm('', $kern_ver);
    $kern_ver;
} @ARGV;

output('all.kernels/.list', map { "$_\n" } @kernels);

sub system_verbose { print join(' ', @_), "\n"; system(@_) }
sub sys { &system_verbose; $? and die }

sub rpm2version {
    my ($kernel_rpm) = @_;
    my $opt = -e $kernel_rpm ? '-qpl' : '-ql';
    `$rpm $opt $kernel_rpm` =~ m!/boot/vmlinuz-(.*)! && $1 or die "can't find vmlinuz in $kernel_rpm (is it installed?)\n";
}

sub extract_installed_rpm {
    my ($installed_dir, $kern_ver) = @_;
    my $local_dir = "all.kernels/$kern_ver";
    mkdir_p("$local_dir");

    sys('cp', "$installed_dir/boot/vmlinuz-$kern_ver", "$local_dir/vmlinuz");
}