#!/usr/bin/perl

use lib qw(/usr/lib/libDrakX);
use Getopt::Long;

use common;
use bootloader;

$::isStandalone = 1; #- not using standalone which messes with @ARGV and usage
c::openlog('bootloader-config' . "[$$]");

$ENV{PATH} = "/sbin:/usr/sbin:$ENV{PATH}";

my %options = (
	       'action=s' => \ (my $action),

	       'label=s' => \ (my $label),
	      );

GetOptions(%options) && $action or die <<'EOF';
       mageia-prepare-upgrade-bootloader-config --action add-entry --label "My Label"
EOF

my @known_actions = qw(add-entry);
$action && member($action, @known_actions) or die "<action> must be one of " . join(' ', @known_actions) . "\n";

$label or die "you must give a label\n";
$image = "/boot/vmlinuz";
( -e $image ) or die "cannot fine image '$image'\n";
$initrd = "/boot/initrd.img";
( -e $initrd ) or die "cannot fine initrd '$initrd'\n";

my $all_hds = fsedit::get_hds();
fs::get_info_from_fstab($all_hds);

my $bootloader = bootloader::read($all_hds);
if (!$bootloader) {
	die "Cannot find a boot loader installed\n";
}

$action =~ s/-/_/g;
$::{$action}->();


#-###############################################################################
sub add_entry() {
    my $root_part = fs::get::root([ fs::get::fstab($all_hds) ]) or die "cannot find root partition\n";

    my $entry = {
		  type => 'image',
		  label => $label,
		  kernel_or_dev => $image,
			root => fs::wild_device::from_part('', $root_part),
			initrd => $initrd,
		 };

    $entry->{vga} = $bootloader->{default_options}{vga} if $bootloader->{default_options}{vga};

    #- normalize append and handle special options
    {
	my ($simple, $dict) = bootloader::unpack_append("$bootloader->{perImageAppend} rw rd.convertfs");
	$entry->{append} = bootloader::pack_append($simple, $dict);
    }

    bootloader::add_entry($bootloader, $entry);
    modify_bootloader();
}


sub modify_bootloader() {
    bootloader::action($bootloader, 'write', $all_hds);
    bootloader::action($bootloader, 'when_config_changed');
}
