#!/usr/bin/perl -w
#
# Copyright (C) 2003, 2004, 2007  Pascal Giard
#
# Author:             Pascal Giard <evilynux@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

use strict;

use Carp;
use File::stat;
use POSIX qw(waitpid);
use Getopt::Long;

eval "use Config::IniFiles;";
if ($@) {
  print "The Config::IniFiles perl module needs to be installed!\n".
    "Please refer to README file.\n";
  exit;
}

use lib '/usr/local/lib/movixmaker-2';
use lib '/usr/lib/movixmaker-2';
use lib 'movixmaker-2';
use config;

use constant FALSE => 0;
use constant TRUE => !FALSE;

use vars qw($NAME %options $xml_root $child_pid $mkisocmd
            $glade_dir $config_file $movixversion
            $diag_feedback $diag_properties
            $statusbar $installed_emovix $tmpfolder
            $destpath $srcpath $help $destination $srcdir $current_path
            @boot_help_langs @menu_langs @remotes @kblayouts @fontsets
            $bootlabels @extra_genisoimage_options $extra_genisoimage_options
            @extra_mplayer_options $extra_mplayer_options
            @unwanted_mplayer_options $unwanted_mplayer_options
            $filelist @real_filenames $codeclist @real_codecfilenames
           );

$NAME="MoviXMaker-2";

# Retrieve options from command line
GetOptions (
	    # 	    "title=s"             => \$title,
	    "tmpDir=s"           => \$options{'tmpdir'},
 	    "output-file=s"       => \$destpath,
 	    "boot-label=s"        => \$options{'bootlabel'},
 	    "extra-genisoimage-options=s"     => \@extra_genisoimage_options,
 	    "extra-mplayer-options=s"     => \@extra_mplayer_options,
 	    "unwanted-mplayer-options=s"  => \@unwanted_mplayer_options,
	    # 	    "make-empty-iso"      => \$make_empty_iso,
 	    "loop=i"              => \$options{'loop'},
 	    "random!"             => \$options{'random'},
 	    "reboot!"             => \$options{'reboot'},
 	    "shut!"               => \$options{'shutdown'},
 	    "eject!"              => \$options{'eject'},
 	    "nodma!"              => \$options{'nodma'},
 	    "nodelete!"           => \$options{'nodelete'},
	    "movixDir=s"          => \$srcpath,
 	    "subtitleFonts=s"     => \$options{'fontset'},
	    "boot-help-lang=s"    => \$options{'boot_help_lang'},
 	    "menu-lang=s"         => \$options{'menu_lang'},
 	    "tv-region=s"         => \$options{'tv_region'},
 	    "remote=s"            => \$options{'remote'},
	    "keyboard=s"          => \$options{'kblayout'},
	    "verbose!"            => \$options{'verbose'},
	    "debug!"              => \$options{'debug'},
	    # 	    "movix-version"       => \$version,
	    "nogui!"              => \$options{'nogui'},
 	    "version"             => \$options{'version'},
	    'help|?'              => \$help
	   );

if ( defined $help ) {
  help();
  exit;
} elsif ( defined $options{'version'} ) {
  print "MoviXMaker-2 $config::version\n";
  exit;
}


# The graphical interface is to be shown
if (!defined $options{'nogui'}) {
  # Trying to load the Gnome perl module
  eval "use Gnome2;";
  if ($@) {
    $options{'nogui'} = TRUE;
    error("The Gnome2 perl module needs to be installed".
	  " in order to use the GUI!\n".
	  "Please refer to README file.\n".
	  "-> Falling back to command line mode.\n");
  } else {
    # Trying to load the GladeXML perl module
    eval "use Gtk2::GladeXML;";
    if ($@) {
      $options{'nogui'} = TRUE;
      error("The Gtk2::GladeXML perl module needs to be installed!\n".
	    "Please refer to README file.\n".
	    "-> Falling back to command line mode.\n");
    } else {
      # Will always work as Gtk2::GladeXML depends on libgtk2-perl
      # which contains Gtk2::SimpleList
      eval "use Gtk2::SimpleList";
    }
  }
}

# MoviXMaker-2 is started in cmdline mode.
if (defined $options{'nogui'}) {
  print "You are in command line mode (--noGUI).\n";

  if (!defined $srcpath) {
    error("You need to specify the *movix* directory!");
    exit;
  }
}
#######################################

$current_path = $0;
$current_path =~ s/movixmaker-2(\.pl)?$//;

if ($0 =~ /^\.\//) {
  $config_file = 'movixmaker-2.conf';
  $glade_dir= '.';
} else {
  $config_file = $config::sysconfdir . '/movixmaker-2.conf';
  $glade_dir = "$current_path../share/movixmaker-2/glade";
}

# Reading the Configuration File
read_config();

$SIG{CHLD} = \&child_dead;
$SIG{__WARN__} = \&Carp::cluck;
#################################

if (defined $options{'nogui'}) {
  set_options();
  get_options();
  prepare_creation();
} else {
  prepare_interface();
  main Gtk2;
}
exit;				# Useless ?
### end main

sub child_dead {
  if ($child_pid) {
    waitpid ($child_pid, 0);
    $child_pid = 0;
  }
}

# Retrieve options from the configuration line
sub read_config {
  my $cfg = new Config::IniFiles( -file => "$config_file" );

  # Global options
  $options{'debug'} = $cfg->val('MoviXMaker','debug')
    if (!defined $options{'debug'});
  $options{'verbose'} = $cfg->val('MoviXMaker','verbose')
    if (!defined $options{'verbose'});
  $options{'nodelete'} = $cfg->val('MoviXMaker','nodelete')
    if (!defined $options{'nodelete'});

  ## *MoviX* options
  # parameters
  $options{'bootlabel'} = $cfg->val('MoviX','bootlabel')
    if (!defined $options{'bootlabel'});
  $options{'boot_help_lang'} = $cfg->val('MoviX','boot_help_lang')
    if (!defined $options{'boot_help_lang'});
  $options{'menu_lang'} = $cfg->val('MoviX','boot_help_lang')
    if (!defined $options{'menu_lang'});
  $options{'tv_region'} = $cfg->val('MoviX','tv_region')
    if (!defined $options{'tv_region'});
  $options{'remote'} = $cfg->val('MoviX','remote')
    if (!defined $options{'remote'});
  $options{'kblayout'} = $cfg->val('MoviX','kblayout')
    if (!defined $options{'kblayout'});
  $options{'fontset'} = $cfg->val('MoviX','fontset')
    if (!defined $options{'fontset'});
  $options{'loop'} = $cfg->val('MoviX','loop')
    if (!defined $options{'loop'});
  $options{'random'} = $cfg->val('MoviX','random')
    if (!defined $options{'random'});
  $options{'shutdown'} = $cfg->val('MoviX','shutdown')
    if (!defined $options{'shutdown'});
  $options{'reboot'} = $cfg->val('MoviX','reboot')
    if (!defined $options{'reboot'});
  $options{'eject'} = $cfg->val('MoviX','eject')
    if (!defined $options{'eject'});
  $options{'nodma'} = $cfg->val('MoviX','nodma')
    if (!defined $options{'nodma'});

  # Other options
  @extra_genisoimage_options = $cfg->val('Others','extra_genisoimage_options')
    if (!defined @extra_genisoimage_options);
  @extra_mplayer_options = $cfg->val('Others','extra_mplayer_options')
    if (!defined @extra_mplayer_options);
  @unwanted_mplayer_options = $cfg->val('Others','unwanted_mplayer_options')
    if (!defined @unwanted_mplayer_options);
}

### callbacks

# The user actually quit the application
sub on_exit_activate {
  Gtk2->main_quit;
}

sub gtk_widget_show {
  my ($w1, $w2) = @_;
  $w2->show ();
}

sub gtk_widget_hide {
  my ($w1, $w2) = @_;
  $w2->hide ();
}

sub about_activate {
  my $about_diag = Gnome2::About->new ($NAME, $config::version,
				       '(C) Pascal Giard, 2003',
				       'MoviXMaker is a Perl GTK+-2/Gnome2 interface to create customized [e]MoviX[2] ISO files.
It is available under the terms of the GPL.',
				       'Pascal Giard <evilynux@users.sf.net>');
  $about_diag->show();
}

sub on_button_create_released {
  my $button = shift;

  $button->set_sensitive(FALSE);
  $destination->set_sensitive(FALSE);
  $srcdir->set_sensitive(FALSE);
  $xml_root->get_widget ("cb_customize")->set_sensitive(FALSE);
  $xml_root->get_widget ("cb_addfiles")->set_sensitive(FALSE);
  $xml_root->get_widget ("cb_addcodecs")->set_sensitive(FALSE);
  $statusbar->set_status("Proceeding...");

  prepare_creation();
}

sub reenable {
  $xml_root->get_widget ("button_create")->set_sensitive(TRUE);
  $xml_root->get_widget ("cb_customize")->set_sensitive(TRUE);
  $xml_root->get_widget ("cb_addfiles")->set_sensitive(TRUE);
  $xml_root->get_widget ("cb_addcodecs")->set_sensitive(TRUE);
  $destination->set_sensitive(TRUE);
  $srcdir->set_sensitive(TRUE);
}


# The verbose_genisoimage_output window gets closed by the user
sub on_fbbutton_released {
  $diag_feedback->hide();
  $statusbar->set_status("$NAME $config::version");
  reenable();
}

# An option as been modified in the Edit/Properties' window
sub on_option_change {
  $xml_root->get_widget ("prop_apply_btn")->set_sensitive (TRUE);
}

# The user is adding a file to the ISO
sub on_add_file {
  my ( $ok_button, $widget, $undef ) = @_;

  foreach my $filename ( $widget->get_selections() ) {
    push( @{$filelist->{'data'}}, $filename );
    push @real_filenames, $filename;
    print "Adding file: $filename\n"
      if ($options{'debug'});
  }

  $widget->hide();
}

# The user is adding a codec to the ISO
sub on_add_codec {
  my ( $ok_button, $widget, $undef ) = @_;

  foreach my $filename ( $widget->get_selections() ) {
    push( @{$codeclist->{'data'}}, $filename );
    push @real_codecfilenames, $filename;
    print "Adding codec: $filename\n"
      if ($options{'debug'});
  }

  $widget->hide();
}

# The user is removing a file from the ISO
sub on_remove_file {
  map( { delete( $filelist->{'data'}[$_] );
	 delete( $real_filenames[$_] ) }
       reverse( $filelist->get_selected_indices() ) );
}

# The user is removing a codec from the ISO
sub on_remove_codec {
  map( { delete( $codeclist->{'data'}[$_] );
	 delete( $real_codecfilenames[$_] ) }
       reverse( $codeclist->get_selected_indices() ) );
}
### end callbacks

###############################
### Options and properties
###############

# Defines if we're using the installed eMoviX dir,
# if so, also update the srcpath.
sub using_installed_emovix {
  my $emovix_path = `echo -n \$(movix-conf 2>/dev/null)`;

  $srcpath = "$emovix_path/" unless (defined $srcpath);
  $installed_emovix = ($srcpath =~ /$emovix_path/) ? TRUE : FALSE;
  print "Using installed eMoviX = $installed_emovix\n"
    if ($options{'debug'} or $options{'nogui'});
}

sub update_options {

  # Boot Labels
  my @bootlabels = split(/\s/ , $bootlabels);
  my $bootlabels_model =
    $xml_root->get_widget ("combo_bootlabels")->get_model;
  $bootlabels_model->clear();

  foreach (@bootlabels) {
    $bootlabels_model->set ($bootlabels_model->append, 0, $_);
  }

  $xml_root->get_widget ("combo_bootlabels")->get_child->
    set_text($options{'bootlabel'});

  # Boot Help Languages
  my $boot_help_langs_model =
    $xml_root->get_widget ("combo_boot_help_langs")->get_model;
  $boot_help_langs_model->clear();

  foreach (@boot_help_langs) {
    $boot_help_langs_model->set ($boot_help_langs_model->append, 0, $_);
  }

  $xml_root->get_widget ("combo_boot_help_langs")->get_child->
    set_text($options{'boot_help_lang'});

  ##
  # *** FIXME: support for menu_lang, remote and tv_region should be added
  ##

  # Fonsets
  my $fontsets_model =
    $xml_root->get_widget ("combo_fontsets")->get_model;
  $fontsets_model->clear();

  foreach (@fontsets) {
    $fontsets_model->set ($fontsets_model->append, 0, $_);
  }

  $xml_root->get_widget ("combo_fontsets")->get_child->
    set_text($options{'fontset'});

  # Keyboard Layouts
  my $kblayouts_model =
    $xml_root->get_widget ("combo_kblayouts")->get_model;
  $kblayouts_model->clear();

  foreach (@kblayouts) {
    $kblayouts_model->set ($kblayouts_model->append, 0, $_);
  }

  $xml_root->get_widget ("combo_kblayouts")->get_child->
    set_text($options{'kblayout'});
}

sub set_options {
  #######
  ## MoviXMaker options
  #######

  # If the graphical interface isn't disabled.
  if (!defined $options{'nogui'}) {
    # Debug mode.
    $xml_root->get_widget ("cb_debug")->set_active($options{'debug'});

    # Verbose genisoimage output.
    $xml_root->get_widget ("cb_verbose")->set_active($options{'verbose'});

    # Donnot delete tmp directory
    $xml_root->get_widget ("cb_nodelete")->set_active($options{'nodelete'});
  }

  # Temporary directory.
  if (defined $options{'tmpdir'} && $options{'tmpdir'} ) {
    $options{'tmpdir'} =~ s/\.$//;
    $options{'tmpdir'} =~ s/([^\/])$/$1\// ;
    # GNU standard : tmpdir defined in the environment variables.
  } elsif (exists $ENV{'TMPDIR'}) {
    $options{'tmpdir'} = $ENV{'TMPDIR'};
    $options{'tmpdir'} =~ s/\.$//;
    $options{'tmpdir'} =~ s/([^\/])$/$1\// ;
  } else {
    $options{'tmpdir'} = "/tmp/";
  }
  $xml_root->get_widget ("tmpdir_entry")->set_text($options{'tmpdir'})
    unless (defined $options{'nogui'});

  #######
  ## genisoimage options
  #######
  if (@extra_genisoimage_options > 0) {
    $extra_genisoimage_options =
      join(' ',split(/,/,join(',',@extra_genisoimage_options)));
    $xml_root->get_widget ("entry_extra_genisoimage_options")->
      set_text($extra_genisoimage_options) unless (defined $options{'nogui'});;
  }
  #######
  ## mplayer options
  #######
  if (@extra_mplayer_options > 0) {
    $extra_mplayer_options = 
      join(' ',split(/,/,join(',',@extra_mplayer_options)));
    $xml_root->get_widget ("entry_extra_mplayer_options")->
      set_text($extra_mplayer_options) unless (defined $options{'nogui'});;
  }

  if (@unwanted_mplayer_options > 0) {
    $unwanted_mplayer_options = 
      join(' ',split(/,/,join(',',@unwanted_mplayer_options)));
    $xml_root->get_widget ("entry_unwanted_mplayer_options")->
      set_text($unwanted_mplayer_options) unless (defined $options{'nogui'});;
  }
  #######
  ## [e]MoviX[] Options
  #######
  my $dest_file = $xml_root->get_widget ("destdir_entry")
    unless (defined $options{'nogui'});

  if ( defined $destpath ) {
    my $pwd = `echo -n \$(pwd)`;
    $destpath =~ s/^\.[^\.]?\//$pwd\//; # if relative path, making it
    # absolute
    $destpath =~ s/\n//;	# removing trailing CR if present
    $destpath =~ s/\.$//;	# removing trailing dot if present
    if ( $destpath =~ /([^\.][^i][^s][^o])$/ ) {
      $destpath =~ s/(\w)$/$1\//;
      $destpath =~ s/(.+)$/$1movix\.iso/; # $destpath has to point
      # to a file.
    }
    $dest_file->set_text($destpath) unless (defined $options{'nogui'});
  } else {
    # No destination file/dir as been specified, using default.
    $dest_file->set_text($options{'tmpdir'} . "movix.iso")
      unless (defined $options{'nogui'});
  }

  if ( defined $srcpath ) {
    my $orig = `echo -n \$(pwd)`;

    chdir $srcpath;
    $srcpath = `echo -n \$(pwd)`; # convert to absolute path
    chdir $orig;

    $srcpath =~ s/([^\/])$/$1\// ; # Add a trailing /
    $xml_root->get_widget ("srcdir_entry")->set_text($srcpath)
      unless (defined $options{'nogui'});

    using_installed_emovix();
  } else {
    using_installed_emovix();
    if (defined $srcpath and !defined $options{'nogui'}) {
      $xml_root->get_widget ("srcdir_entry")->set_text($srcpath);
    }
  }

  if (!defined $options{'nogui'}) {
    # Default boot help language.
    if (defined $options{'boot_help_lang'}) {
      $xml_root->get_widget ("combo_boot_help_langs")->get_child->
	set_text($options{'boot_help_lang'});
    }

    ##
    # *** FIXME : menu_lang, remote and tv_region need to be handled.
    ##

    # Default keyboard layout.
    if (defined $options{'kblayout'} && $options{'kblayout'}) {
      $xml_root->get_widget ("combo_kblayouts")->get_child->
	set_text($options{'kblayout'});
    }

    # Default fontset.
    if (defined $options{'fontset'} && $options{'fontset'}) {
      $xml_root->get_widget ("combo_fontsets")->get_child->
	set_text($options{'fontset'});
    }

    # Default boot label.
    if (defined $options{'bootlabel'} && $options{'bootlabel'}) {
      $xml_root->get_widget ("combo_bootlabels")->get_child->
	set_text($options{'bootlabel'});
    }

    # Play movies in random order
    $xml_root->get_widget ("cb_random")->set_active($options{'random'});

    # Power off PC after playing all CD files
    $xml_root->get_widget ("cb_shut")->set_active($options{'shutdown'});

    # Reboot PC after playing all CD files
    $xml_root->get_widget ("cb_reboot")->set_active($options{'reboot'});

    # Eject the CD
    $xml_root->get_widget ("cb_eject")->set_active($options{'eject'});

    # Disable DMA
    $xml_root->get_widget ("cb_nodma")->set_active($options{'nodma'});

    # Loop N times the playlist
    if (defined $options{'loop'} && $options{'loop'}) {
      $xml_root->get_widget ("spinbutton_loop")->set_value($options{'loop'});
    }

    # Renders the apply button insensitive
    $xml_root->get_widget ("prop_apply_btn")->set_sensitive(FALSE);
  }
}

# Take the options from the view and update the ones in the model
sub get_options {

  ## MoviXMaker options
  #######
  if (!defined $options{'nogui'}) {
    # Debug mode.
    $options{'debug'} =
      $xml_root->get_widget ("cb_debug")->get_active || 0;

    # Verbose genisoimage output.
    $options{'verbose'} = $xml_root->get_widget ("cb_verbose")->get_active || 0;

    # Donnot delete tmp dir.
    $options{'nodelete'} = $xml_root->get_widget ("cb_nodelete")->get_active || 0;
  }

  # Temporary directory.
  $options{'tmpdir'} = $xml_root->get_widget ("fileentry_tmpdir")->get_full_path(0)
    unless (defined $options{'nogui'});
  $options{'tmpdir'} =~ s/([^\/])$/$1\// ;

  #######
  ## genisoimage options
  #######
  if (!defined $options{'nogui'}) {
    $extra_genisoimage_options =
      $xml_root->get_widget ("entry_extra_genisoimage_options")->get_text;
    #######
    ## mplayer options
    #######
    $extra_mplayer_options =
      $xml_root->get_widget ("entry_extra_mplayer_options")->get_text;
    $unwanted_mplayer_options =
      $xml_root->get_widget ("entry_unwanted_mplayer_options")->get_text;
    #######
    ## [e]MoviX[] Options
    #######
    # Default boot help language.
    $options{'boot_help_lang'} = 
      $xml_root->get_widget ("combo_boot_help_langs")->get_child->get_text;

    # Default keyboard layout.
    $options{'kblayout'} =
      $xml_root->get_widget ("combo_kblayouts")->get_child->get_text;

    # Default fontset.
    $options{'fontset'} = $xml_root->get_widget ("combo_fontsets")->get_child->
      get_text;

    # Default bootlabel.
    $options{'bootlabel'} =
      $xml_root->get_widget ("combo_bootlabels")->get_child->get_text;

    # Play movies in random order
    $options{'random'} = $xml_root->get_widget ("cb_random")->get_active || 0;

    # Power off PC after playing all CD files
    $options{'shutdown'} = $xml_root->get_widget ("cb_shut")->get_active || 0;

    # Reboot PC after playing all CD files
    $options{'reboot'} = $xml_root->get_widget ("cb_reboot")->get_active || 0;

    # Eject the CD
    $options{'eject'} = $xml_root->get_widget ("cb_eject")->get_active || 0;

    # Disable DMA
    $options{'nodma'} = $xml_root->get_widget ("cb_nodma")->get_active || 0;

    # Loop the playlist N times.
    $options{'loop'} = $xml_root->get_widget ("spinbutton_loop")->get_value_as_int;

    # MoviX option
    $options{'menu_lang'} =
      $xml_root->get_widget("optionmenu_menu_lang")->get_menu->get_active->get_name;

    # TV region
    $options{'tv_region'} =
      $xml_root->get_widget("optionmenu_tv_region")->get_menu->get_active->get_name;

    # Remote control
    $options{'remote'} =
      $xml_root->get_widget("optionmenu_remote")->get_menu->get_active->get_name;

    ## End of options fetching

    $xml_root->get_widget ("prop_apply_btn")->set_sensitive(FALSE);
  }

  if ($options{'debug'}) {
    print STDERR <<EOL
DEBUG = $options{'debug'}
VERBOSE = $options{'verbose'}
NODELETE = $options{'nodelete'}
EXTRA_GENISOIMAGE_OPTIONS = "$extra_genisoimage_options"
EXTRA_MPLAYER_OPTIONS = "$extra_mplayer_options"
UNWANTED_MPLAYER_OPTIONS = "$unwanted_mplayer_options"
TMPDIR = "$options{'tmpdir'}"
BOOT_HELP_LANG = "$options{'boot_help_lang'}"
MENU_LANG = "$options{'menu_lang'}"
TV_REGION = "$options{'tv_region'}"
REMOTE = "$options{'remote'}"
KBLAYOUT = "$options{'kblayout'}"
FONTSET = "$options{'fontset'}"
BOOTLABEL = "$options{'bootlabel'}"
LOOP = $options{'loop'}
RANDOM = $options{'random'}
SHUTDOWN = $options{'shutdown'}
REBOOT = $options{'reboot'}
EJECT = $options{'eject'}
NODMA = $options{'nodma'}
EOL
  }
}
########################

#################
## Display XWindow
########
sub prepare_interface {
  Gtk2->init;
  Gnome2::Program->init ($NAME, $config::version, 'libgnomeui');

  $xml_root = new Gtk2::GladeXML ($glade_dir."/MoviXMaker-2.glade");
  $xml_root->signal_autoconnect_from_package ('main');

  my $main_win = $xml_root->get_widget ("MoviXMaker");
  $main_win->set_title ("$NAME $config::version");

  $statusbar = $xml_root->get_widget ("statusbar");
  $destination = $xml_root->get_widget ("fileentry_dest");
  $srcdir = $xml_root->get_widget ("fileentry_src");

  # Feedback Dialog
  $diag_feedback = $xml_root->get_widget ("diag_feedback");
  # Properties Dialog
  $diag_properties = $xml_root->get_widget ("diag_properties");
  $diag_properties->set_transient_for ($main_win); # diag_properties ber alles

  # file selector dialog
  my $diag_fileselection = $xml_root->get_widget ("diag_fileselection");
  $diag_fileselection->set_select_multiple(TRUE);

  # prevent modifications of comboboxes values
  $xml_root->get_widget ("combo_bootlabels")->get_child->set_editable(FALSE);
  $xml_root->get_widget ("combo_boot_help_langs")->get_child->
    set_editable(FALSE);
  $xml_root->get_widget ("combo_kblayouts")->get_child->set_editable(FALSE);
  $xml_root->get_widget ("combo_fontsets")->get_child->set_editable(FALSE);

  # Filelist creation (files that will be add to the ISO image)
  $filelist =
    Gtk2::SimpleList->new ('Path to file or directory' => 'text');

  # Gtk2::SimpleList is derived from Gtk2::TreeView, so you can
  # do anything you'd do to a treeview.
  $filelist->set_rules_hint (TRUE);
  $filelist->get_selection->set_mode ('multiple');
  map { $_->set_resizable (TRUE) } $filelist->get_columns;

  # packed into a scrolled window...
  my $scrolled_files = $xml_root->get_widget ("scrolledwindow_addfiles");
  $scrolled_files->add ($filelist);
  # all in one go
  $scrolled_files->show_all;

  # Codeclist creation (codecs added to the dics image)
  $codeclist =
    Gtk2::SimpleList->new ('Path to codec file or directory' => 'text');

  # Gtk2::SimpleList is derived from Gtk2::TreeView, so you can
  # do anything you'd do to a treeview.
  $codeclist->set_rules_hint (TRUE);
  $codeclist->get_selection->set_mode ('multiple');
  map { $_->set_resizable (TRUE) } $codeclist->get_columns;

  # packed into a scrolled window...
  my $scrolled_codecs = $xml_root->get_widget ("scrolledwindow_addcodecs");
  $scrolled_codecs->add ($codeclist);
  # all in one go
  $scrolled_codecs->show_all;

  #######################
  # Options specified at command line
  # are taken into account here
  ########
  set_options;
  get_options();
  #########################

  $statusbar->set_status("Welcome!");
}

# Display error dialog
sub error {
  my ($err_msg) = @_;
  print STDERR "ERROR : $err_msg\n"
    if ($options{'debug'} || (defined $options{'nogui'}));
  return if (defined $options{'nogui'});

  $statusbar->set_status("An error has occured!");

  my $diag_error =
    new Gtk2::MessageDialog ($xml_root->get_widget ('MoviXMaker'),
			     'modal', 'error', 'ok', $err_msg);
  $diag_error->set_title("Error creating disc image");
  $diag_error->signal_connect (response => sub {$_[0]->destroy});
  reenable;
  $diag_error->show_all;
}

# Display warning dialog
sub warning {
  my ($err_msg) = @_;
  print STDERR "WARNING : $err_msg\n"
    if ($options{'debug'} | (defined $options{'nogui'}));
  return if (defined $options{'nogui'});

  my $diag_warning =
    new Gtk2::MessageDialog ($xml_root->get_widget ('MoviXMaker'),
			     'modal', 'warning', 'ok', $err_msg);
  $diag_warning->signal_connect (response => sub {$_[0]->destroy});
  $diag_warning->show_all;
}


sub create_iso {
  my ($progress, $diag_progress, $fbtext, $fbtextbuffer, $output, $coutput);

  # Create temp dir and update the global variable
  $tmpfolder = create_tmp_folder();
  if (!$tmpfolder) {
    $diag_feedback->hide();
    reenable();
    return;
  }


  unless (defined $options{'nogui'}) {
    $fbtext = $xml_root->get_widget ("fbtext");

    # Verbose genisoimage in dialog if enabled
    if ($options{'verbose'}) {
      $fbtextbuffer = $fbtext->get_buffer;
      $fbtextbuffer->delete($fbtextbuffer->get_iter_at_offset(0),
			    $fbtextbuffer->get_iter_at_offset(-1));
      $diag_feedback->show_all();
    }

    $statusbar->set_status("Calling genisoimage...");
  }

  my $isolinux = ($movixversion =~ /^eMoviX/) ?
    "eMoviX/boot/" : "isolinux/";

  ############## TAKEN FROM mkmovixiso ###########
  ##################
  ### Standard booting options, from SysLinux docs
  ### and from slackware installation CD README
  ###############
  my $bootOptions = "-no-emul-boot -boot-load-size 4 -boot-info-table ".
    "-b ${isolinux}isolinux.bin -c ${isolinux}isolinux.boot ".
      "-sort ${isolinux}iso.sort";
  ###############
  ### Standard genisoimage options: -v=>verbose, -r=>rock-ridge,
  ####                          -J=>Joliet,  -f=>follow symbolic links
  ##############
  my $stdOptions = "-v -r -J -f";
  #########################################

  $child_pid = open(CMDEXEC,"cd $tmpfolder ; genisoimage -o $destpath ".
                    "$stdOptions -V '$movixversion' $extra_genisoimage_options ".
                    "$bootOptions -A '$movixversion' . 2>&1 |");
  print STDERR "CHILD_PID : $child_pid\n" if ($options{'debug'});

  unless (defined $options{'nogui'}) {
    $progress = $xml_root->get_widget ("progressbar");
    $diag_progress = $xml_root->get_widget ("diag_progress");

    $progress->set_fraction(0);
    $diag_progress->show;
  }

  while (<CMDEXEC>) {
    if ( $_ =~ /([0-9]{1,2}).*done.*(estimate)/i ) {
      my $value = $1;
      print STDERR "WRITING PROGRESS : $value %\n"
	if ($options{'debug'} || (defined $options{'nogui'}));
      $progress->set_fraction($value/100) unless (defined $options{'nogui'});
    } elsif ( $_ =~ /(writing|scanning)/i and (!defined $options{'nogui'})) {
      $diag_progress->set_title($1);
      $statusbar->set_status($1);
    } elsif ( $_ =~ /genisoimage:\sWarning:\s(.*)/ ) {
      print STDERR "WARNING : $1\n"
	if ($options{'debug'} || (defined $options{'nogui'}));
      ######
      # Detecting genisoimage errors and rejecting Warnings
    } elsif ( $_ =~ /genisoimage:(.*)/ ) {
      $diag_progress->hide unless (defined $options{'nogui'});
      error($1);
    }

    $output = $_;
    $coutput .= $_;

    unless (defined $options{'nogui'}) {
      if ($options{'verbose'}) {
	my $iter = $fbtextbuffer->get_iter_at_offset(-1); # -1 = end of buffer
	$fbtextbuffer->insert($iter, $output);
      }

      while (Gtk2->events_pending) {
	Gtk2->main_iteration();
      }
    }
  }

  ######
  # Detecting if it created the disc image
  if ( $coutput =~ /extents\swritten\s\(([0-9]+\sMb)\)/i ) {
    my $disc_image_size = $1;
    print STDERR "WROTE : $disc_image_size\n"
      if ($options{'debug'} or (defined $options{'nogui'}));
    unless (defined $options{'nogui'}) {
      $diag_progress->hide;
      $statusbar->set_status("Disc image created! ($disc_image_size)");
      reenable();
    }
    ######
    # Special treatment for genisoimage --help
  } elsif ( $coutput =~ /Usage:\s(.*)/ ) {
    $coutput =~ s/^.*Warning.*\n//; # We don't want the warnings to be displayed
    if (defined $options{'nogui'}) {
      print "$coutput\n";
    } else {
      $diag_progress->hide;
      $fbtextbuffer->delete($fbtextbuffer->get_iter_at_offset(0),
			    $fbtextbuffer->get_iter_at_offset(-1));
      $fbtextbuffer->insert($fbtextbuffer->get_iter_at_offset(0), $coutput);
      $diag_feedback->show_all();
      reenable();
    }
  }
  ######
  # Deleting the temporary directory
  system "rm -rf '$tmpfolder'" if ( -e $tmpfolder && !$options{'nodelete'});
}

# Detects the version of movix contained in the specified directory.
sub get_movix_version {
  return unless (defined $srcpath);

  using_installed_emovix();

  if ($installed_emovix) {

    $movixversion = "eMoviX-" . `echo -n \$(movix-version 2>/dev/null)`;

    $statusbar->set_status("Detected $movixversion.")
      unless (defined $options{'nogui'});

    print STDERR "FOUND : $movixversion\n"
      if ($options{'debug'} or (defined $options{'nogui'}));

    return;
  }

  $statusbar->set_status("Attempting to detect MoviX version...")
    unless (defined $options{'nogui'});

  $movixversion = "";

  my $versionFile;

  if ( -e $srcpath."/NEWS") {
    my $nbrLines = `wc -l ${srcpath}/NEWS | cut -d " " -f 1`;
    chop $nbrLines;

    $versionFile = ($nbrLines > 0) ? $srcpath."/NEWS" : $srcpath."/ChangeLog";
  } else {
    $versionFile = $srcpath."/ChangeLog";
  }

  if ( open CF, $versionFile ) {
    my $version = "";
    while (<CF>) {
      $version = $_;
      last if ($version =~ m/\*\se?MoviX/);
    }
    close CF;

    if ( $version =~ /(e?MoviX2?[-\s]([0-9]\.){2}[0-9]((pre|rc)[0-9]{1,2})?(cvs[0-9]{8})?)/ ) {
      $movixversion = $1;

      $statusbar->set_status("Detected $movixversion.")
	unless (defined $options{'nogui'});

      print STDERR "FOUND : $movixversion\n"
	if ($options{'debug'} or (defined $options{'nogui'}));

    } else {
      if (defined $options{'nogui'}) {
	print "Not a valid *MoviX* directory.\n";
      } else {
	$statusbar->set_status("Not a valid *MoviX* directory.");
      }

    }
  } else {
    if (defined $options{'nogui'}) {
      print "Not a valid *MoviX* directory.\n";
    } else {
      $statusbar->set_status("Not a valid *MoviX* directory.");
    }
    return;
  }
}

# Tries to detect the available boot help languages
sub get_boot_help_languages {
  my $dir = ($movixversion =~ /^eMoviX/) ?
    "${srcpath}translations" : "${srcpath}boot-messages";
  opendir (LP, $dir);
  my @files = grep { /^[a-z]{2,3}$/ && -d "$dir/$_" } readdir(LP);
  closedir LP;

  @files = qw(en) unless (@files);

  return @files;
}

# Tries to detect the available menu languages
sub get_menu_languages {
  return @boot_help_langs if ( $movixversion =~ /^eMoviX/ );

  my $dir = "${srcpath}src/movix";

  opendir (LP, $dir);
  my @files = grep { /^menu\.conf\.([a-z]{2,3})$/ } readdir(LP);
  closedir LP;

  # We only want a list of the available languages
  if (@files) {
    foreach (@files) {
      $_ =~ s/^menu\.conf\.//;
    }
  }

  @files = qw(en) unless (@files);

  return @files;
}

# Tries to detect the available menu languages
sub get_remotes {

  my $dir = ($installed_emovix) ?
    "${srcpath}remotes" : "${srcpath}src/movix/remotes";

  opendir (LP, $dir);
  my @files = grep { /^lircrc\.([a-z]+)$/ } readdir(LP);
  closedir LP;

  # We only want a list of the available languages
  if (@files) {
    foreach (@files) {
      $_ =~ s/^lircrc\.//;
    }
  }

  return @files;
}

# Detects the available keyboard layouts
sub get_kblayouts {
  my $dir = "${srcpath}keyboard-i18n";
  opendir (LP, $dir);
  my @files = grep { /^[a-z]{2,3}$/ && -d "$dir/$_" } readdir(LP);
  closedir LP;

  @files = qw(us) unless (@files);

  return @files;
}

# Detects the available fontsets
sub get_fontsets {
  my $dir = "${srcpath}mplayer-fonts";
  opendir (LP, $dir);
  my @files = grep { /^[a-z]{2,}$/ && -d "$dir/$_" } readdir(LP);
  closedir LP;

  @files = qw(latin) unless (@files);

  return @files;
}

# Detects the available bootlabels
sub get_bootlabels {
  my $list;
  my $src = $installed_emovix ? "" : "src/";

  open FILE, $srcpath."${src}isolinux/isolinux.cfg" or die $!;
  while ( <FILE> ) {
    chomp;
    $list .= "$1 " if ($_ =~ /^label\s([a-zA-Z0-9]+)$/);
  }
  close (FILE);
  return $list;
}

sub validate_boot_help_language {
  my $choosen_lang;
  foreach my $lang (@boot_help_langs) {
    $choosen_lang = $options{'boot_help_lang'}
      if ($lang =~ /$options{'boot_help_lang'}/);
  }
  return "en" unless $choosen_lang;
}

sub validate_menu_language {
  my $choosen_lang;
  foreach my $lang (@menu_langs) {
    $choosen_lang = $options{'menu_lang'}
      if ($lang =~ /$options{'menu_lang'}/);
  }
  return "en" unless $choosen_lang;
}

sub validate_remote {
  my $choosen_remote;
  foreach my $remote (@remotes) {
    $choosen_remote = $options{'remote'}
      if ($remote =~ /$options{'remote'}/);
  }
  return "none" unless $choosen_remote;
}

sub validate_kblayout {
  my $choosen_kblayout;
  foreach my $kblayout (@kblayouts) {
    $choosen_kblayout = $options{'kblayout'}
      if ($kblayout =~ /$options{'kblayout'}/);
  }
  return "us" unless $choosen_kblayout;
}

sub validate_fontset {
  my $choosen_fontset;
  foreach my $fontset (@fontsets) {
    $choosen_fontset = $options{'fontset'}
      if ($fontset =~ /$options{'fontset'}/);
  }
  return "latin" unless $choosen_fontset;
}

sub validate_bootlabel {
  my $choosen_bootlabel;
  my $default = $1		# eMoviX's default boot
    if ($movixversion =~ /e?(MoviX2?)/); # label is MoviX
  $choosen_bootlabel = $options{'bootlabel'}
    if $bootlabels =~ /\W$options{'bootlabel'}\W/;
  return $default unless $choosen_bootlabel;
}

sub get_movix_options {
  @boot_help_langs = get_boot_help_languages;
  @menu_langs = get_menu_languages;
  @remotes = get_remotes;
  @kblayouts = get_kblayouts;
  @fontsets = get_fontsets;
  $bootlabels = get_bootlabels();
  $options{'boot_help_lang'} = validate_boot_help_language();
  $options{'menu_lang'} = validate_menu_language();
  $options{'remote'} = validate_remote();
  $options{'kblayout'} = validate_kblayout();
  $options{'fontset'} = validate_fontset();
  $options{'bootlabel'} = validate_bootlabel();

  if ($options{'debug'} or (defined $options{'nogui'})) {
    print STDERR "FOUND BOOT HELP LANGUAGE(S) : ";
    foreach my $file (@boot_help_langs) {
      print STDERR "$file ";
    }
    print STDERR ".\n";
    print STDERR "FOUND MENU LANGUAGE(S) : ";
    foreach my $file (@menu_langs) {
      print STDERR "$file ";
    }
    print STDERR ".\n";
    print STDERR "FOUND REMOTE(S) : ";
    foreach my $file (@remotes) {
      print STDERR "$file ";
    }
    print STDERR ".\n";
    print STDERR "FOUND KBLAYOUT(S) : ";
    foreach my $file (@kblayouts) {
      print STDERR "$file ";
    }
    print STDERR ".\n";
    print STDERR "FOUND FONTSET(S) : ";
    foreach my $file (@fontsets) {
      print STDERR "$file ";
    }
    print STDERR ".\n";
    print STDERR
      "FOUND BOOTLABELS : " . $bootlabels . ".\n".
	"EFFECTIVE BOOT HELP LANG : " . $options{'boot_help_lang'} . ".\n";

    if (defined $options{'menu_lang'}) {
      print STDERR "EFFECTIVE MENU LANG : " . $options{'menu_lang'} . ".\n";
    }

    if (defined $options{'tv_region'}) {
      print STDERR "EFFECTIVE TV REGION : " . $options{'tv_region'} . ".\n";
    }

    if (defined $options{'remote'}) {
      print STDERR "EFFECTIVE REMOTE : " . $options{'remote'} . ".\n";
    }

    print STDERR
      "EFFECTIVE KBLAYOUT : " . $options{'kblayout'} . ".\n".
	"EFFECTIVE FONTSET : " . $options{'fontset'} . ".\n".
	  "EFFECTIVE BOOTLABEL : " . $options{'bootlabel'} . ".\n";
  }
}

sub prepare_creation {
  if (!defined $options{'nogui'}) {
    $destpath = $destination->get_full_path(0);
    $srcpath = $srcdir->get_full_path(0);
  }

  $srcpath =~ s/([^\/])$/$1\// ; # Add a trailing /

  print "Preparing ISO using movixDir: " . $srcpath . "\n"
    if ($options{'debug'} or (defined $options{'nogui'}));

  get_movix_version();

  if (!$srcpath || !$destpath) {
    if (defined $options{'nogui'}) {
      print "Specify a dir and destination file!\n";
      exit;
    } else {
      $statusbar->set_status("Specify a dir and destination file!");
      reenable();
      return;
    }
  }

  if (!$movixversion) {
    if (defined $options{'nogui'}) {
      print "$srcpath is not a [e]MoviX[] directory!\n".
	"Please contact me if you believe it is.\n";
      exit;
    } else {
      $statusbar->set_status("That's not a [e]MoviX[] dir!");
      reenable();
      return;
    }
  }

  # Now that we know that it's a valid *MoviX* path, let's detect
  # what's available.
  get_movix_options();

  # From the cmdline, we go directly to ISO creation.
  if (defined $options{'nogui'}) {
    create_iso();
    return;
  }

  # Update the interface with avail. options
  update_options();

  ### FIXME: Very ugly dialog handling ###
  if ($xml_root->get_widget ("cb_addfiles")->get_active
      or $xml_root->get_widget ("cb_addcodecs")->get_active) {
    $xml_root->get_widget ("btn_customize_next")->show;
    $xml_root->get_widget ("btn_customize_ok")->hide;
  }

  if ($xml_root->get_widget ("cb_addfiles")->get_active) {
      if ($xml_root->get_widget ("cb_addcodecs")->get_active) {
	$xml_root->get_widget ("btn_addfiles_next")->show;
      } else {
	$xml_root->get_widget ("btn_addfiles_ok")->show;
      }
  }

  if ($xml_root->get_widget ("cb_addcodecs")->get_active) {
    $xml_root->get_widget ("btn_addfiles_next")->show;
    $xml_root->get_widget ("btn_addfiles_ok")->hide;

    if ($xml_root->get_widget ("cb_customize")->get_active) {
      $xml_root->get_widget ("btn_addfiles_previous")->show;
    } else {
      $xml_root->get_widget ("btn_addfiles_previous")->hide;
    }
  }

  # Does the user want to customize the disc image ?
  if (!$xml_root->get_widget ("cb_customize")->get_active
      and !$xml_root->get_widget ("cb_addfiles")->get_active
      and !$xml_root->get_widget ("cb_addcodecs")->get_active) {
    # Directly creating the image, no customization
    create_iso();
    return;

  # Show dialog to customize disc image
  } elsif ($xml_root->get_widget ("cb_customize")->get_active){
    $xml_root->get_widget ("diag_customize")->show();

  # Show dialog to add files to the disc image
  } elsif ($xml_root->get_widget ("cb_addfiles")->get_active){
    $xml_root->get_widget ("diag_addfiles")->show();

  # Show dialog to add codecs to the disc image
  } elsif ($xml_root->get_widget ("cb_addcodecs")->get_active){
    $xml_root->get_widget ("diag_addcodecs")->show();
  }
  ### END OF FIXME: Very ugly dialog handling ###

}

# Creates the directory that will be used to create the ISO disc image
sub create_tmp_folder {
  my $date = `date +%s`;
  chop $date;

  my $src = $installed_emovix ? "" : "src/";
  my $origDir = `echo -n \$(pwd)`;

  my $isolinux = ($movixversion =~ /^eMoviX/) ?
    "boot" : "isolinux";

  my $tmpDir = "${options{'tmpdir'}}movix-$date";
  print "Temporary directory: $tmpDir\n" if ($options{'debug'});

  mkdir  "$tmpDir";

  if ( ! -e $tmpDir ) {
    my $badpath = $1 if ( $tmpDir =~ /(.*\/).*$/ );

    if ( ! -w $badpath ) {
      error("$badpath is not writable");
    } elsif ( ! -e $badpath ){
      error("$badpath does not exist!");
    } else {
      error("Unknown error when trying to create $tmpDir!");
    }
    return;
  }

  chdir  "$tmpDir";

  if ($movixversion =~ /^eMoviX/) {
    mkdir "eMoviX";
    chdir "eMoviX";
  }

  # Adding user specified multimedia files
  foreach my $filename (@real_filenames) {
    system "ln -s $filename ." if ($filename);
  }

  # Include the movies that were copied into the src/ dir
  system "ln -s ${srcpath}${src}/* .";

  system "rm -f movix";
  mkdir  "movix";
  system "ln -s ${srcpath}${src}movix/* movix";

  system "rm -f isolinux";
  mkdir  $isolinux;
  system "cp -r ${srcpath}${src}isolinux/* ${isolinux}";
  if ($movixversion =~ /^eMoviX/) {
    system "ln -s `pwd`/boot/kernel/vmlinuz ${isolinux}/vmlinuz";
  }

  # Remote controls when creating from a eMoviX package.
  if ($movixversion =~ /^eMoviX/ and
      -d "${srcpath}${src}movix/remotes" ) {
    mkdir "remotes";
    system "ln -s ${srcpath}${src}movix/remotes/* remotes";
    system "rm -rf movix/remotes";
  }

  if ( -e "${srcpath}${src}mplayer" ) {
    system "rm -f mplayer";
    mkdir  "mplayer";
    system "ln -s ${srcpath}${src}mplayer/* mplayer";
  }

  if ( -e $srcpath . "keyboard-i18n/" . $options{'kblayout'} ) {
    if ($movixversion =~ /^eMoviX/) {
      # Link the isolinux boot-keymap to the selected keyboard layout
      system "ln -s ${srcpath}keyboard-i18n/${options{'kblayout'}}".
	"/bootkey.map boot/bootkey.map";
      # Link the selected shell keymap
      system "ln -s ${srcpath}keyboard-i18n/${options{'kblayout'}}".
	"/shellkey.map boot/shellkey.map";
    } else {
      # Link the isolinux boot-keymap to the selected keyboard layout
      system "ln -s ${srcpath}keyboard-i18n/${options{'kblayout'}}".
	"/bootkey.map isolinux/bootkey.map";
      # Link the selected shell keymap
      system "ln -s ${srcpath}keyboard-i18n/${options{'kblayout'}}".
	"/shellkey.map isolinux/shellkey.map";
    }
  }

  # Usefull because the user might not be able to write to the original
  # isolinux.bin
  system "rm -f ${isolinux}/isolinux.bin";
  system "cp ${srcpath}${src}isolinux/isolinux.bin ${isolinux}/isolinux.bin";

  system "rm -f ${isolinux}/*.txt";

  # Translations for eMoviX <= 0.9.0pre1, MoviX and MoviX2
  if ( -e $srcpath . "boot-messages/" . $options{'boot_help_lang'} ) {
    system "ln -s ${srcpath}boot-messages/${options{'boot_help_lang'}}/*txt".
      " ${isolinux}";
  }
  # Translations for eMoviX >= 0.9.0rc1
  if ( -e $srcpath . "translations/" . $options{'boot_help_lang'} ) {
    mkdir "help";
    mkdir "mplayer";
    system "rm -f ${isolinux}/*.msg";
    system "ln -s ${srcpath}translations/${options{'boot_help_lang'}}/*.{txt,msg}".
      " ${isolinux}";
    system "ln -s ${srcpath}translations/${options{'boot_help_lang'}}/*.{sh,man,sub}".
      " help";
    system "ln -s ${srcpath}translations/${options{'boot_help_lang'}}/menu.conf".
      " mplayer";
  }


  if ( -e $srcpath . "mplayer-fonts" ) {
    my $fontDir = ($movixversion =~ /^eMoviX/) ?
      "font" : "mplayer/font";
    system "mkdir -p $fontDir";
    system "ln -s ${srcpath}mplayer-fonts/$options{'fontset'}/* $fontDir"
      if ( -e $srcpath . "mplayer-fonts/" . $options{'fontset'} );
    system "ln -s ${srcpath}mplayer-fonts/*.ttf $fontDir/.";
    if ($movixversion =~ /^eMoviX/) {
      # FIXME: User should choose this
      system "ln -s ${srcpath}mplayer-fonts/Vera.ttf mplayer/subfont.ttf";
    }
  }


  if ( -e $srcpath . "mplayer/codecs") {
    system "rm -f mplayer/codecs" and mkdir -p "mplayer/codecs"
      and system "ln -s " . $srcpath . "mplayer/codecs/* mplayer/codecs";
  }

  if (! -e "mplayer/codecs") {
    system "mkdir -p mplayer/codecs";

    foreach my $filename (@real_codecfilenames) {
      system "ln -s $filename mplayer/codecs" if ($filename);
    }
  }

  create_isolinuxcfg($isolinux);

  # Creating the file containing the default [e]MoviX[2] boot parameters
  my $bootrc = ($movixversion =~ /^eMoviX/) ?
    "movix/movixrc" : "movix/bootrc";

  create_bootrc($bootrc);

  if ($movixversion =~ /^eMoviX/) {
    system "rm -f keyboard-i18n mplayer-fonts translations backgrounds";
    system "rm -f Makefile* {boot,movix,mplayer,remotes}/Makefile*"
      if (!$installed_emovix);
  }

  chdir  "$origDir";
  return $tmpDir;
}


# Creates the syslinux configuration file
sub create_isolinuxcfg {
  my ($isolinux) = shift;

  return if (! defined $options{'bootlabel'} );

  my $isolinuxcfg = "default $options{'bootlabel'}\n";

  open CFG, "${isolinux}/isolinux.cfg";
  <CFG>;
  while (<CFG>) {
    $isolinuxcfg .= $_;
  }
  close CFG;

  system "rm -f ${isolinux}/isolinux.cfg";
  open CFG, "> ${isolinux}/isolinux.cfg";
  print CFG $isolinuxcfg;
  close CFG;
}


# Creates the boot configuration file for eMoviX/MoviX/MoviX2
sub create_bootrc {
  my $file = shift;

  system "rm -f $file" if( -e $file );

  open BOOTRC, "> " . $file;

  print BOOTRC "EXTRA-MPLAYER-OPTIONS=$extra_mplayer_options\n"
    if (defined $extra_mplayer_options && $extra_mplayer_options);

  print BOOTRC "UNWANTED-MPLAYER-OPTIONS=$unwanted_mplayer_options\n"
    if (defined $unwanted_mplayer_options && $unwanted_mplayer_options);

  print BOOTRC "LOOP=$options{'loop'}\n" if ($options{'loop'} =~ /[0-9]+/);
  print BOOTRC "SHUT=y\n"     if ($options{'shutdown'} != 0);
  print BOOTRC "REBOOT=y\n"   if ($options{'reboot'} != 0);
  print BOOTRC "RANDOM=y\n"   if ($options{'random'} != 0);
  print BOOTRC "EJECT=y\n"    if ($options{'eject'} != 0);
  print BOOTRC "DMA=n\n"      if ($options{'nodma'} != 0);

  print BOOTRC "KB=$options{'kblayout'}\n"
    if ($options{'kblayout'} =~ /[a-z]{2}(\-[a-z]{2})?/);

  print BOOTRC "LANGUAGE=$options{'menu_lang'}\n"
    if ($options{'menu_lang'} =~ /[a-z]{2}(\-[a-z]{2})?/);

  print BOOTRC "REGION=$options{'tv_region'}\n"
    unless ($options{'tv_region'} =~ /none/);

  print BOOTRC "REMOTE=$options{'remote'}\n"
    unless ($options{'remote'} =~ /none/);

  close BOOTRC;
}


####  Command line help
######################
sub help {
  print
    "Usage: " . $0 . " [options]
Note: All options that may be abbreviated to uniqueness
      can use a single dash.
Options:

 Generic:

   --verbose               Verbose genisoimage output
   --debug                 Debug mode (kind of movixmaker verbose)
   --version               Displays MoviXMaker-2's version and exits
   --nogui                 Do not show the graphical interface
   --nodelete              Don't delete temporary directory
   --output-file=<file>    Name [with full path!] of the output iso image
   --tmpDir=<path>         Directory that will contain the temporary files

 *MoviX*:
   --boot-label=<label>    Make MoviX boot by default with your favorite label
   --boot-help-lang=<lang> Specify the language of the CD boot help messages
   --menu-lang=<lang>      Specify the MoviX/MPlayer menu language
   --tv-region=<region>    Specify the tv region among: ntsc, ntsc-j,
                           pal, pal-60, pal-nc, pal-m, pal-m60, pal-x, secam.
   --remote=<remote>       Specify the remote control among: hauppauge,
                           haupserial, hauppauge2, logitech, pctv, abit,
                           realmagic, grundig_tp720, kingman_code_026.
   --keyboard=<lang>       Specify the keyboard layout to use
   --movixDir=<dir>        Location of the *movix* directory
   --loop=<k>              Make MPlayer play k times your files before stopping
                           [0=infinity]
   --random                Make MPlayer play your files in random order
   --nodma                 Make MoviX run with DMA turned off
                           (fixes old-HDs issues)
   --eject                 Make MoviX eject the CD once it finished playing
   --reboot                Make MoviX reboot the PC once it finished playing
   --shut                  Make MoviX shut the PC off once it finished playing
   --extra-genisoimage-options=\"opt1 opt2 ...\"
                           Extra options for genisoimage
   --extra-mplayer-options=\"opt1 opt2 ...\"
                           Extra options for MPlayer
   --unwanted-mplayer-options=\"opt1 opt2 ...\"
                           Options you want to be sure MPlayer will not use
   --help                  This help
   --subtitleFonts=fontset Specify which font set will be included in iso image.\n";
}

# Man pages for MoviXMaker-2
=pod

=head1 NAME

MoviXMaker-2 - Easily create customized eMoviX/MoviX/MoviX2 disc images

=head1 SYNOPSIS

    movixmaker-2[.pl] [--version|--help] [--verbose] [--debug]
                  [--nogui] [--nodelete] [--boot-help-lang=Language]
                  [--menu-lang=Language] [--subtitleFonts=FontSet]
                  [--tv-region=Region] [--remote=RemoteControl]
                  [--keyboard=KbLayout] [--movix=MovixSrcDir]
                  [-o=OutputFile] [-t=TempDir] [-b=BootLabel]
                  [--loop=NbrOfLoops] [--random] [--nodma]
                  [--eject] [--reboot] [--shut]
                  [--extra-genisoimage-options="opt1 opt2 ..."]
                  [--extra-mplayer-options="opt1 opt2 ..."]
                  [--unwanted-mplayer-options="opt1 opt2 ..."]

=head1 DESCRIPTION

I<MoviXMaker> is a simple Perl command line utility or a
GTK+-2/Gnome2/GladeXML interface to create customized
eMoviX/MoviX/MoviX ISO files.

  It includes disk image customization possibilities such as :
   - boot help language, subtitle fontset, boot label selection.
   - you can specify [e]MoviX[] parameters such as :
     movix/mplayer menu language (language), keyboard layout (kb),
     tv region (region), remote control (remote), loop, random,
     shutdown (shut), reboot, eject, dma, extra_mplayer_options and
     unwanted_mplayer_options.

=head1 OPTIONS

All options that may be abbreviated to uniqueness can use a single dash.

=head2 --version

=over

Displays MoviXMaker-2's version and exits.

=back

=head2 --help

=over

Display help messages [similar to this help] then exits.

=back

=head2 --verbose

=over

Verbose genisoimage output.

=back

=head2 --debug

=over

Debug mode (kind of movixmaker-2 verbose).

=back

=head2 --nogui

=over

Do not display the graphical interface.

=back

=head2 --nodelete

=over

Don't delete temporary directory.

=back

=head2 --boot-help-lang=I<Language>

=over

Specify the language of the CD boot help messages.

=back

=head2 --menu-lang=I<Language>

=over

Specify the MoviX/MPlayer menu language.

=back

=head2 --tv-region=I<Region>

=over

Specify the tv region among: ntsc, ntsc-j, pal, pal-60, pal-nc, pal-m,
pal-m60, pal-x, secam.

=back

=head2 --remote=I<Remote>

=over

Specify the remote control among: hauppauge, haupserial, hauppauge2,
logitech, pctv, abit, realmagic, grundig_tp720, kingman_code_026.

=back

=head2 --subtitleFonts=I<FontSet>

=over

Specify which font set will be included in iso image.

=back

=head2 -k I<KbLayout>, --keyboard=I<KbLayout>

=over

Specify the keyboard layout to use.

=back

=head2 -m I<MovixSrcDir>, --movixDir=I<MovixSrcDir>

=over

Location of the *MoviX* directory.

=back

=head2 -o I<OutputFile>, --output-file=I<OutputFile>

=over

Name [with full path!] of the output iso image.

=back

=head2 -t I<TempDir>, --tmpDir=I<TempDir>

=over

Directory that will contain the temporary files.

=back

=head2 -b I<BootLabel>, --boot-label=I<BootLabel>

=over

Make *MoviX* boot with your favorite label (new default boot label).

=back

=head2 --loop=I<NbrOfLoops>

=over

Don't delete temporary directory.

=back

=head2 --random

=over

Don't delete temporary directory.

=back

=head2 --nodma

=over

Make *MoviX* run with DMA turned off (fixes old-HDs issues).

=back

=head2 --eject

=over

Make *MoviX* eject the CD once it finished playing.

=back

=head2 --reboot

=over

Make *MoviX* reboot the PC once it finished playing.

=back

=head2 --shut

=over

Make *MoviX* poweroff the PC once it finished playing.

=back

=head2 --extra-genisoimage-options="opt1 opt2 ..."

=over

Extra options for genisoimage.

=back

=head2 --extra-mplayer-options="opt1 opt2 ..."

=over

Extra options for MPlayer.

=back

=head2 --unwanted-mplayer-options="opt1 opt2 ..."

=over

Options you want to be sure MPlayer will not use.

=back

=head1 AUTHOR

Pascal Giard, E<lt>evilynux@yahoo.comE<gt>

=head1 COPYRIGHT

Copyright (C) 2003, 2004 Pascal Giard E<lt>evilynux@yahoo.comE<gt>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

=head1 SEE ALSO

L<Gnome2(3)>, L<Gtk2(3)>, L<Getopt::Long(3)>, L<Config::IniFiles(3)>

=cut

  ########################
