#! /usr/bin/perl

use POSIX;
use Getopt::Long;
use Pod::Usage;
use Bootloader::Tools;
use strict;

my %oper;
my ($opt_args, $opt_update, $opt_initrd, $opt_add_image, $opt_default, $opt_title)
    = ("",0,'','',undef,'');

GetOptions (\%oper,
    'add-kernel=s' => \$opt_add_image,
    'bootloader-probe' ,
    'update-kernel' => \$opt_update,
    'make-default',
    'args=s'      => \$opt_args,
    'initrd=s'      => \$opt_initrd,
    'title=s' => \$opt_title)
    or pod2usage(2);

if (defined $oper{'bootloader-probe'}){
  print Bootloader::Tools::GetBootloader();
  exit 0;
}

my $lib = InitLibrary();

if ($opt_add_image ne ''){
  print "add kernel\n";
  my @sections = @{$lib->GetSections ()};
  my $section = { 'name' => $opt_title,
                  'append' => $opt_args,
                  'type' => "image",
                  'initrd' => $opt_initrd,
                  'image' => $opt_add_image,
                  'original_name' => 'linux',
                  '__modified' => '1',
                  'root' => $lib->GetMountPoints()->{"/"}};
  unshift @sections, $section;
  $lib->SetSections (\@sections);
  print "set sections\n";
  if (defined $oper{'make-default'}){
    my $glob_ref = $lib->GetGlobalSettings();
    $glob_ref->{"default"} = $section->{"name"};
    $lib->SetGlobalSettings ($glob_ref);
  }
  $lib->WriteSettings(1);
  $lib->UpdateBootloader (1);
  print "bootloader updated\n";
  Bootloader::Tools::DumpLog($lib->{"loader"});
}
