#! /usr/bin/env perl
#
# (c) 2009 Technische Universität Dresden
#
# Adam Lackorzynski <adam@os.inf.tu-dresden.de>
#

use strict;
use warnings;

BEGIN { unshift @INC, $ENV{L4DIR}.'/tool/lib'
           if $ENV{L4DIR} && -d $ENV{L4DIR}.'/tool/lib/L4';}

use L4::ModList;
use File::Temp qw/tempdir/;
use File::Basename qw/basename/;

my $qemu         = $ENV{QEMU}         || 'qemu';
my $kernelname   = $ENV{KERNEL}       || 'bootstrap';
my $module_path  = $ENV{SEARCHPATH}   || ".";
my $qemu_options = $ENV{QEMU_OPTIONS} || "";
my $modulesfile  = shift;
my $entryname    = shift;
my $tmpdir       = tempdir(CLEANUP => 1); 

sub qemu_get_file
{
  my $mod = shift;
  my $fp;

  if (exists $mod->{opts}->{uncompress})
    {
      $fp = L4::ModList::get_file_uncompressed_or_die($mod->{file}, $module_path,
                                                      $tmpdir);
    }
  else
    {
      $fp = L4::ModList::search_file_or_die($mod->{file}, $module_path);
    }

  my $bn = basename($fp);

  if ($bn ne $mod->{command})
    {
      my $link = "$tmpdir/" . $mod->{command};
      symlink $fp, $link;
      $fp = $link;
    }

  my $arguments = $mod->{args_quoted};
  $arguments =~ s/,/,,/g;
  $fp.' '.$arguments;
}


die "No entry name given" unless defined $entryname;

my %entry = L4::ModList::get_module_entry($modulesfile, $entryname,
                                          $module_path);

my @mods = @{$entry{mods}};
my $kernel = L4::ModList::search_file_or_die($entry{bootstrap}{file}, $module_path);
L4::ModList::fetch_remote_file($_->{file}) foreach (@{$entry{mods}});
my $initrd = join(',', map { qemu_get_file($_) } @mods);
my $args = $entry{bootstrap}{args_quoted};
$args =~ s/"/'/;
$args = "" unless defined $args;

my $qemu_cmd =
      "$qemu -kernel $kernel -append \"$args\" ".
      "-initrd \"$initrd\" $qemu_options";

print "$qemu_cmd\n";
system("$qemu_cmd");
