#!/usr/bin/perl

use lib "../perl-install";
use common;
use pkgs;

my @ALLOWED_LANGS = split(' ', first(cat_('move.pm') =~ /ALLOWED_LANGS = qw\((.*)\)/));
my @langs = map { /^../; $& } @ALLOWED_LANGS;

@ARGV <= 1 or die "usage: make_live [live_location=/tmp/live_tree]\n";

my $kernel_version = do {
    my @l = glob_('/export/Mandrake/RPMS/kernel-2.*');
    @l >= 1 or die "can't find kernel";
    @l <= 1 or die "too many kernels";
    first(`rpm -qp --qf '%{name}' $l[0]` =~ /kernel-(.*)/);
};

sub installPackages {
    output_p("$::prefix/etc/rpm/macros", "%_install_langs " . join(":", @langs) . "\n");
    rename '/etc/rpm/macros', '/etc/rpm/macros.';
    system('cp', "$::prefix/etc/rpm/macros", '/etc/rpm/macros');

    mkdir_p("$::prefix/var/lib/rpm");
    mkdir_p("$::prefix/root/drakx");


    undef *install_any::setDefaultPackages;
    *install_any::setDefaultPackages = sub {};

    undef *install_any::getFile;
    *install_any::getFile = sub {
	my ($f, $o_method) = @_;
	log::l("getFile $f:$o_method");
	open(my $F, '/export/' . install_any::relGetFile($f)) or return;
	$F;
    };
    install_any::setPackages(my $o = $::o = { 
					     prefix => $::prefix, 
					     meta_class => 'desktop', 
					     default_packages => [
                                 qw(XFree86-server XFree86-xfs XFree86-FBDev),
				 qw(openssh-server), #- fred wants it
				 qw(alsa-utils newt), #- newt
				 qw(davfs nfs-utils samba-server sane-backends xsane xsane-gimp ntp),
                                 qw(acpi acpid), #- so that removing acpi=ht will work
				 qw(mountloop),	#- crypted folders
				 qw(dnotify),	#- notification of /etc changes
				 qw(mandrake_doc-move-en mandrake_doc-move-fr mandrake_doc-move-drakxtools-en mandrake_doc-move-drakxtools-fr),
				 qw(zcip dhcp-client dhcpcd ppp kdenetwork-kppp rp-pppoe pptp-adsl speedtouch speedtouch_mgmt nfs-utils-clients samba-client tmdns wireless-tools adiusbadsl pcmcia-cs), #- network conf
                                 qw(cups cups-drivers foomatic-db gimpprint hpoj libnet-snmp mtools mtoolsfm nmap printer-filters printer-testpages printer-utils scli xojpanel xpp), #- printer stuff
				 qw(ATI_GLX NVIDIA_GLX),
                                 "kernel-smp-$kernel_version",
				 qw(hcfpcimodem hsflinmodem ltmodem), "NVIDIA_nforce-$kernel_version",
				 qw(xinput), #- for some mice
                                 qw(perl-Term-Readline-Gnu binutils emacs-X11 bash-completion),  #- allow debugging move
                                 qw(openssh-askpass-gnome),  #- openssh-askpass for mountloop doesn't allow to click on ok/cancel buttons
                                 qw(clanbomber freeciv-client freeciv-server crack-attack kdegames),  #- more games
                                 qw(numlock shorewall),
                                 qw(xawtv zapping),  #- tv apps
                                 qw(scribus scribus-i18n-de scribus-i18n-fr),  #- John Jablonski says it's so much useful
                                                                 ],
					    });

    my %compssUsersChoice = map { $_ => 1 } map { @{$_->{flags}} } values %{$o->{compssUsers}};
    $compssUsersChoice{$_} = 1 foreach 'SYSTEM', 'DVD', 'USB', 'SOUND', 'BURNER', 'UTF8', 'DOCS', 'TV', '3D', 'INSTALL';
    $compssUsersChoice{qq(LOCALES"$_")} = 1 foreach @langs;

    pkgs::setSelectedFromCompssList($o->{packages}, \%compssUsersChoice, 4, 0);

    my @toInstall = pkgs::packagesToInstall($o->{packages});
    local $ENV{DURING_INSTALL} = 1;
    $ENV{LD_LIBRARY_PATH} = "/lib:/usr/lib:/usr/X11R6/lib:/usr/lib/qt3/lib";
    pkgs::install($::prefix, 0, \@toInstall, $o->{packages});

    eval { fs::umount("$::prefix/proc") };

    unlink "/etc/rpm/macros";
    rename "/etc/rpm/macros.", "/etc/rpm/macros";
}

sub config_X_proprietary_drivers {
    unlink "$::prefix/usr/lib/libGL.so";

    my %name_to_Driver = (NVIDIA_GLX => 'nvidia', ATI_GLX => 'fglrx');

    my $lib = 'libGL.so.1';
    symlinkf("/etc/X11/$lib", "$::prefix/usr/lib/$lib");
    foreach (keys %name_to_Driver) {
	my ($full_name) = run_program::rooted_get_stdout($::prefix, 'rpm', '-ql', $_) =~ m!/usr/lib/(\Q$lib\E\..*)! or die '';
	symlinkf($full_name, "$::prefix/usr/lib/$lib.$name_to_Driver{$_}");
    }
    #- remove the dirty hack done by NVIDIA_kernel-xxx proprietary package
    #- we do it by hand when needed
    substInFile { $_ = '' if /^nvidia$/ } "$::prefix/etc/modules";
}

my $cwd = chomp_(`pwd`);
$::prefix = $ARGV[0] || '/tmp/live_tree';
print "Making live in $::prefix directory.\n";

eval { fs::umount("$::prefix/proc") };
#eval { rm_rf($::prefix) };
output_p("$::prefix/etc/fstab", "none /proc proc defaults 0 0\n");

installPackages();

run_program::rooted($::prefix, 'ldconfig');
any::fix_broken_alternatives();
run_program::rooted($::prefix, 'fc-cache');  #- generate cache in all directories mentioned in config file


    #- system

eval { rm_rf("$::prefix/lib/i686") }; # de-complexify, use the default on any arch

eval { config_X_proprietary_drivers() };

substInFile {
    #- /lib is ro, for the moment we don't save, we'll see later if we may want to save (using /var/dev-state for example)
    s|.*lib/dev-state.*||;
} "$::prefix/etc/devfsd.conf";

substInFile {
    #- don't use shadow passwords since pwconv overwrites /etc/shadow hence contents will be lost for usb key
    s|\s*shadow||;
} "$::prefix/etc/pam.d/system-auth";

substInFile { 
    #- remove this line which D-state mounting /home again
    #- we don't know what this line is for
    $_ = "# $_" if /Mounting other filesystems/;
} "$::prefix/etc/init.d/netfs";

#- remove services we start ourselves from chkconfig system
substInFile {
    s|chkconfig:|chkconfig-disabled:|;
} "$::prefix/etc/rc.d/init.d/$_" foreach qw(xfs dm devfsd syslog);

#- we're not using sysv init, we need to replace these
unlink "$::prefix/sbin/$_" foreach qw(halt reboot);

#- provide a way for speedtouch users of free version to escape
if (!-e "$::prefix/usr/share/speedtouch/mgmt.o") {
    symlink '/etc/mgmt.o', "$::prefix/usr/share/speedtouch/mgmt.o";
}

#- we don't want everyone to have the same ssh key :)
system("rm -f $::prefix/etc/ssh/*key*");


    #- XFree

#- don't want the relative path, prefering the absolute path
symlinkf('/var/lib/xkb', "$::prefix/etc/X11/xkb/compiled"); 

#- Xsession wants to start first-time
unlink "$::prefix/usr/X11R6/bin/drakfw";


    #- KDE

symlinkf('/etc/X11/ksycoca', "$::prefix/usr/share/services/ksycoca");

unlink "$::prefix/usr/share/autostart/$_.desktop" foreach 'klipper', 'korgac', 'kalarmd.autostart';

update_gnomekderc("$::prefix/usr/share/config/kdesktoprc", ScreenSaver => (Lock => 'true'));

#- remove CD-based applications from simplified menu
substInFile {
    foreach my $app (qw(kaudiocreator kscd k3b)) {
        s|.*command="$app".*||;
    }
} "$::prefix/usr/lib/menu/simplified/mandrake_desk";

#- remove "Login Manager" module from kcontrol, rpmdrake stuff
unlink "$::prefix/usr/lib/menu/$_" foreach qw(kdebase-kdm rpmdrake);

touch("$::prefix/etc/menu/enable_simplified");

substInFile {
    s/mandrake_doc-(en|fr)/mandrake_doc-move-$1/g;
} "$::prefix/usr/lib/menu/simplified/mandrake_desk";

substInFile {
    s!/es/Starter.html/!/en/Starter.html/!;
} "$::prefix/usr/share/mdk/mandrakegalaxy/mdkgalaxy-es.html";

$ENV{LC_ALL} = 'en_US'; #- update-menus doesn't work when there is no locale (aka locale "C")
run_program::rooted($::prefix, 'update-menus', '-n');

run_program::rooted($::prefix, 'nspluginscan'); #- must be run before kbuildsycoca for the ksycoca to be flash plugin aware

$ENV{HELP_BROWSER} = "kfmclient openProfile webbrowsing";
$ENV{BROWSER} = "kfmclient openProfile webbrowsing";
$ENV{DESKTOP} = "kde";
foreach (@ALLOWED_LANGS) {
    $ENV{LC_ALL} = $_;
    run_program::rooted($::prefix, 'kbuildsycoca');
    cp_af("$::prefix/tmp/kde-root/ksycoca", "$::prefix/usr/share/services/ksycoca-$_");
}


    #- Mandrake

substInFile {
    s|Mandrake Linux release (\S+) \(.*\)|Mandrake Move release $1 (Moyoto)|;
} "$::prefix/etc/mandrake-release";

#- fix mandrake galaxy version download
substInFile {
    s/Mandrake%20Control%20Center\.desktop/Configure%20your%20computer.desktop/;
    s/logiciels\.// if $next;
    $next = s/, et installez de nouveaux/.../;
} "$::prefix/usr/share/mdk/mandrakegalaxy/mdkgalaxy-fr.html";

#- remove uncessary wizards, especially from appearing in MCC
unlink "$::prefix/usr/sbin/$_" foreach qw(drakautoinst drakboot drakfloppy drakgw drakedm drakfont rpmdrake MandrakeUpdate rpmdrake-remove edit-urpm-sources.pl);
unlink "$::prefix/usr/bin/$_" foreach qw(userdrake);

#- selecting language must be done from drakx anyway
unlink "$::prefix/usr/bin/localedrake";

#- drakxtools contains a broken unneeded file
unlink "$::prefix/usr/lib/libDrakX/modem.pm";