summaryrefslogtreecommitdiffstats
path: root/draklive
blob: d52724e48af8706c419c4ea5ec3e1f6ef3a682cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
#!/usr/bin/perl

# draklive $Id: draklive 150793 2007-04-05 12:08:47Z blino $

# Copyright (C) 2005 Mandriva
#                    Olivier Blin <oblin@mandriva.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, 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

use lib qw(/usr/lib/libDrakX);
use strict;
use MDK::Common;
use common;
use list_modules;
use fs;
use modules;
use run_program;
use Getopt::Long;
use Pod::Usage;
use File::Temp;
use IO::Handle; #- autoflush
use MDV::Draklive::Utils;
use MDV::Draklive::Live;
use MDV::Draklive::Progress;
use MDV::Draklive::Loopback;
use MDV::Draklive::Initrd;
use MDV::Draklive::Config;
use MDV::Draklive::Storage;

sub get_syslinux_path {
    my ($media, $opts) = @_;
    '/' . $media->{storage} . '/syslinux' . ($opts->{boot} && '-boot-' . $opts->{boot}) . '.cfg';
}

sub need_media_specific_boot {
    my ($live) = @_;
    to_bool(list_selected_loopbacks($live));
}

sub get_default_append {
    my ($live, $opts) = @_;
    join(' ',
         if_(!need_media_specific_boot($live),
             'root=' . $live->{media}->get_media_source_for_nash),
         if_($live->{system}{vga_mode},
             'splash=silent',
             'vga=' . $live->{system}{vga_mode}),
         ($opts->{append} ? $opts->{append} : $live->{system}{append} ? $live->{system}{append} : ()),
     );
}

sub get_bootloader_timeout {
    my ($live) = @_;
    defined $live->{media}{bootloader_timeout} ? $live->{media}{bootloader_timeout} : 4;
}

my @syslinux_boot_files = qw(/vmlinuz /syslinux/bootlogo /help.msg);

sub build_syslinux_cfg {
    my ($live, $media, $opts) = @_;
    my $append = get_default_append($live, $opts);
    #- syslinux wants files at root (used with vfat fs)
    my $to_root = $media->get_boot_setting('fs', $opts) eq 'vfat';
    my $boot = $live->get_media_prefix('boot', $opts->{boot});
    my ($initrd, $kernel, $bootlogo, $help) = map { $to_root ? basename($_) : $_ }
      map { $boot . $_ } $media->get_initrd_path, @syslinux_boot_files;
    my $has_bootlogo = $live->{system}{gfxboot} &&
      -e ($live->get_builddir . $live->{prefix}{build}{boot} . '/syslinux/bootlogo');
    my $timeout = get_bootloader_timeout($live) * 10;
    my $title = $media->{title} || $live->{media}{title};
    join("\n",
         "default $title",
         "prompt 1",
         "timeout $timeout",
         "display help.msg",
         $has_bootlogo ? "ui gfxboot.com $bootlogo" : "display $help",
         (map {
             my ($name, $cmdline) = @$_;
             $name =~ s/\s/_/g;
	     if ($name eq "harddisk") {
		 "label " . $name,
		 "    localboot 0x80";
	     } else {
		"label " . ($name || $title),
		"    kernel $kernel",
		"    append initrd=$initrd $append $cmdline";
	    }
         } group_by2('' => '', @{$media->{boot_entries}})),
         "",
     );
}

sub build_grub_cfg {
    my ($live, $media, $opts, $device) = @_;
    #- FIXME? first partition is hardcoded for loopback (master images)
    #- FIXME? use find_partition_index
    my ($part_nb) = $device =~ m!/dev/loop! ? 1 : $device =~ /(\d+)$/;
    my $part_idx = $part_nb - 1;
    my $initrd = $media->get_initrd_path;
    build_grub_cfg_raw($live, $media, $initrd, $opts, $part_idx);
}

sub build_grub_cfg_raw {
    my ($live, $media, $initrd, $opts, $part_idx) = @_;
    #- FIXME: use the bootloader module from drakx
    my $grub_part = "(hd0" . (defined $part_idx ? "," . $part_idx : "") . ")";
    my $boot = $live->get_media_prefix('boot'); #- FIXME handle boot media
    #- remove prefix if installing bootloader on separate /boot partition
    $media->{partitions}[$part_idx]{mntpoint} eq $boot and $boot = "";

    my $title = $media->{title} || $live->{media}{title};
    join("\n",
         "timeout " . get_bootloader_timeout($live),
         if_($live->{system}{gfxboot}, "gfxmenu $grub_part" . $boot . "/gfxmenu"),
         "default 0",
         (map {
             my ($name, $cmdline) = @$_;
             "title " . $title . if_($name, " ($name)"),
             "kernel $grub_part" . $boot . "/vmlinuz " . get_default_append($live, $opts) . if_($cmdline, " $cmdline"),
             if_($initrd, "initrd " . $boot . $initrd);
         } group_by2('' => '', @{$live->{system}{boot_entries}})),
         if_(defined $opts->{oem_rescue_idx},
             #- FIXME: factorize with above, build_grub_cfg_entry($media)
             "title " . $live->{oem_rescue}{media}{title},
             "kernel (hd0,$opts->{oem_rescue_idx})" . $boot . "/vmlinuz " . $live->{oem_rescue}{append},
             "initrd (hd0,$opts->{oem_rescue_idx})" . $boot . $media->get_initrd_path,
         ),
         "",
     );
}

sub get_langs {
    my ($live) = @_;
    uniq(
        (ref $live->{regions} ? @{$live->{regions}{$live->{settings}{region}}} : ()),
        @{$live->{system}{langs_always}}
    );
}

sub install_system {
    my ($live) = @_;

    my $repository = $live->{settings}{repository} . '/' . $live->{settings}{arch};

    my $drakx_in_chroot = $repository . '/misc/drakx-in-chroot';
    my $remote_repository = $repository =~ m!^(ftp|http)://! && $1;
    if ($remote_repository) {
        my $local_drakx_in_chroot = $live->get_builddir . $live->{prefix}{build}{scripts} . '/drakx-in-chroot';
        mkdir_p(dirname($local_drakx_in_chroot));
        run_('curl', '--silent', '-o', $local_drakx_in_chroot, $drakx_in_chroot)
          or die "unable to get drakx-in-chroot from remote repository\n";
        $drakx_in_chroot = $local_drakx_in_chroot;
    }

    local %ENV = (%ENV, %{$live->{system}{install_env}});
    $ENV{DRAKLIVE_LANGS} = join(':', get_langs($live));
    $ENV{DRAKLIVE_REGION} = $live->{settings}{region};
    run_({ setarch => $live->{settings}{arch} },
	 'perl', $drakx_in_chroot,
         $repository,
         $live->get_system_root,
         if_($live->{system}{auto_install}, '--auto_install', $live->{settings}{config_root} . '/' . $live->{system}{auto_install}),
         if_($live->{system}{patch_install}, '--defcfg', $live->{settings}{config_root} . '/' . $live->{system}{patch_install}),
         if_($live->{system}{rpmsrate}, '--rpmsrate', $live->{settings}{config_root} . '/' . $live->{system}{rpmsrate}),
         ($live->{system}{stage2_updates} ? (map { ('--stage2-update', $live->{settings}{config_root} . '/' . $_->[0], $_->[1]) } @{$live->{system}{stage2_updates}}) : ()),
    ) or die "unable to install system chroot\n";
    post_install_system($live);
}

sub configure_draklive_resize {
    my ($live) = @_;

    my $resizable_loopback = find { $_->{min_size} } @{$live->{mount}{dirs} || []};
    if ($resizable_loopback) {
        my $media_loopbacks = $live->get_media_prefix('loopbacks');
        my $ext = $loop_types{$resizable_loopback->{type}}{extension};
        output($live->get_system_root . '/etc/sysconfig/draklive-resize', <<EOF);
DRAKLIVE_RESIZE=yes
LOOPBACK=$live->{prefix}{live}{mnt}$live->{prefix}{media}{mnt}${media_loopbacks}$resizable_loopback->{path}$ext
TYPE=$resizable_loopback->{fs}
MIN_SIZE=$resizable_loopback->{min_size}
MOUNT=$live->{prefix}{live}{mnt}$resizable_loopback->{mountpoint}_resized
OLD_MOUNT=$live->{prefix}{live}{mnt}$resizable_loopback->{mountpoint}
UNION=/
EOF
    }
}

sub copy_files_to {
    my ($live, $files, $root) = @_;
    foreach (@$files) {
        my ($source, $dest, $o_opts) = @$_;
        $dest = $root . '/' . $dest;
        mkdir_p($dest =~ m|/$| ? $dest : dirname($dest));
        my @sources = MDV::Draklive::Utils::glob__($live->{settings}{config_root} . '/' . $source);
        print STDERR "copying @sources to $dest\n";
        cp_af(@sources, $dest);
        my $o_perm = $o_opts && $o_opts->{mode};
        chmod $o_perm, $dest if $o_perm;
    }
}

sub join_lists {
    my ($separator, $head, @lists) = @_;
    @{$head || []}, map { $separator, @$_ } @lists;
}

sub remove_files_from {
    my ($files, $root) = @_;
    run_('find', $root, '(', join_lists('-o', map { [ '-name', $_ ] } @$files), ')', '-exec', 'rm', '-r', '{}', ';')
      if $files && @$files;
}

sub post_install_system {
    my ($live) = @_;

    my $previous_umask = umask;
    #- workaround buggy installation of directories that are not owned by any packages
    umask 022;

    #- copy resolv.conf for name resolution to work when adding media
    cp_f("/etc/resolv.conf", $live->get_system_root . "/etc");

    #- remove previous draklive leftovers if needed
    run_({ root => $live->get_system_root }, 'urpmi.removemedia', '-a');

    foreach (@{$live->{system}{additional_media}}) {
        run_({ root => $live->get_system_root }, 'urpmi.addmedia', if_($_->{distrib}, '--distrib'), $_->{name}, $_->{path})
          or die "unable to add media from $_->{path}\n";
        @{$_->{packages}} or next;
        run_({ root => $live->get_system_root, setarch => $live->{settings}{arch} },
	     'urpmi', '--auto', '--no-verify-rpm', if_(!$_->{distrib}, '--searchmedia', $_->{name}), @{$_->{packages}})
          or die "unable to install packages from $_->{path}\n";
    }

    #- additional rpms may have dependencies in additional media
    if (@{$live->{system}{rpms}}) {
        my $rpm_tmp_dir = '/tmp/draklive_rpms';
        mkdir_p($live->get_system_root . $rpm_tmp_dir);
        cp_f((map { $live->{settings}{config_root} . '/' . $_ } @{$live->{system}{rpms}}), $live->get_system_root . $rpm_tmp_dir);
        run_({ root => $live->get_system_root, setarch => $live->{settings}{arch} },
	     'urpmi', '--auto', '--no-verify-rpm',
             map { $rpm_tmp_dir . '/' . basename($_) } @{$live->{system}{rpms}})
          or die "unable to install additional system rpms\n";
        rm_rf($live->get_system_root . $rpm_tmp_dir);
    }

    #- remove urpmi media added by drakx-in-chroot and additional media, they're unusable
    run_({ root => $live->get_system_root }, 'urpmi.removemedia', '-a');

    my $erase = join(' ', @{$live->{system}{erase_rpms}});
    run_({ root => $live->get_system_root, setarch => $live->{settings}{arch} },
	 'sh', '-c', "rpm -qa $erase | xargs rpm -e ") if $erase;

    run_({ root => $live->get_system_root }, 'chkconfig', '--del', $_) foreach @{$live->{system}{disable_services}};

    #- make sure harddrake is run:
    #- if previous HW config file is empty, we assumes DrakX has just completed the installation
    #- (do it in chroot, or else Storable from the build box may write an incompatible config file)
    run_({ root => $live->get_system_root },
         'perl', '-MStorable', '-e', qq(Storable::store({ UNKNOWN => {} }, '/etc/sysconfig/harddrake2/previous_hw')));

    #- remove some build-machine specific configuration
    substInFile { undef $_ if /^[^#]/ } $live->get_system_root . $_
      foreach qw(/etc/fstab /etc/mtab /etc/modprobe.conf /etc/modprobe.preload /etc/iftab /etc/shorewall/interfaces /etc/mdadm.conf /etc/resolv.conf);
    unlink($_) foreach map { glob($live->get_system_root . $_) } @{$live->{system}{remove_files} || []};

    if ($live->{system}{modules_conf}) {
        local $::prefix = $live->get_system_root;
        local *modules::write_preload_conf = sub {}; #- FIXME, make this an option
        my $modules_conf = modules::any_conf->vnew;
        put_in_hash($modules_conf, $live->{system}{modules_conf});
        $modules_conf->write;
    }

    output_with_perm($live->get_system_root . '/etc/fstab', 0644,
                     $live->{mount}{overlay}
                     ? "none / $live->{mount}{overlay} rw 0 0\n"
                     : $live->{media}->get_media_setting('source') . " / " . $live->{media}->get_media_setting('fs') . " defaults 1 1\n"
                 );

    #- interactive mode can lead to race in initscripts
    #- (don't use addVarsInSh from MDK::Common, it breaks shell escapes)
    substInFile { s/^PROMPT=.*/PROMPT=no/ } $live->get_system_root . '/etc/sysconfig/init';

    configure_draklive_resize($live);

    if ($live->{system}{preselect_kdm_user}) {
        #- preselect specified user in kdm
        my $kdm_cfg = $live->get_system_root . '/etc/kde/kdm/kdmrc';
        update_gnomekderc($kdm_cfg, 'X-:0-Greeter' => (PreselectUser => 'Default', DefaultUser => $live->{system}{preselect_kdm_user})) if -f $kdm_cfg;
    }

    #- apply patches and install files after the configuration is cleaned
    #- to allow special configuration files (especially modprobe.preload)
    foreach (@{$live->{system}{patches}}) {
        my $patch = $live->{settings}{config_root} . '/' . $_;
        my @args = ('-p0', '-d', $live->get_system_root, '-i', $patch);
        run_program::run('patch', '>', '/dev/null', '--dry-run', '-f', '-R', @args) || run_('patch', @args)
            or die "unable to apply patch " . $patch . "\n";
    }

    copy_files_to($live, $live->{system}{files}, $live->get_system_root);
    my @no_install_files = map { $_->[1] } grep { $_->[2] && $_->[2]{no_install} } @{$live->{system}{files}};
    output_p($live->get_system_root . '/etc/draklive-install.d/remove.d/draklive', map { "$_\n" } @no_install_files);

    eval { rm_rf($live->get_builddir . $live->{prefix}{build}{files}) };
    mkdir_p($live->get_builddir . $live->{prefix}{build}{files});
    if ($live->{media}{files}) {
        copy_files_to($live, $live->{media}{files}, $live->get_builddir . $live->{prefix}{build}{files});
    }
    remove_files_from($live->{media}{remove_files}, $live->get_builddir . $live->{prefix}{build}{files});

    run_({ setarch => $live->{settings}{arch} },
	 "chroot", $live->get_system_root, "bash", "-c", $live->{system}{postInstall}) if $live->{system}{postInstall};

    write_dist_lists($live);

    umask $previous_umask;
}

sub write_dist_lists {
    my ($live) = @_;

    my $lst = $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . '.lst';
    mkdir_p(dirname($lst));
    run_("chroot " . $live->get_system_root . " rpm -qa | sort > " . $lst);

    my $full = $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . '.lst.full';
    mkdir_p(dirname($full));
    run_("chroot " . $live->get_system_root .
           qq( sh -c "rpm -qa --qf '%{size}      \t%{name}\n' | sort -n" > ) . $full);

    my $leaves = $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . '.lst.leaves';
    mkdir_p(dirname($leaves));
    run_("chroot " . $live->get_system_root .
           qq( sh -c "urpmi_rpm-find-leaves | xargs rpm -q --qf '%{size}       \t%{name}\n' | sort -n" > ) . $leaves);

    require lang;
    my @live_langs = get_langs($live);
    my @langs = grep { member(lang::locale_to_main_locale($_), @live_langs) } lang::list_langs();
    my $langs_file = $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . '.langs';
    output_p($langs_file, map { lang::l2name($_) . " (" . $_ . ")\n" } sort(@langs));
}

sub umount_external_filesystem {
    my ($live) = @_;
    my $mnt = $live->get_system_root . "/mnt/";
    eval { fs::mount::umount("$mnt/$_") } foreach all($mnt);
}

sub expand_file_list {
    my ($live, @files) = @_;
    map {
        $_->{path} ?
          $_->{path} :
          chomp_(cat_(glob(($_->{rooted} && $live->get_system_root) . $_->{source})));
    } @files;
}

#- hardlink recursively file list to a directory
sub hardlink_filtered {
    my ($src, $dest, $files) = @_;
    mkdir_p($dest);
    my $pwd = $ENV{PWD};
    chdir($src);
    my $list_file = tmpnam();
    output_p($list_file, map { "$_\n" } grep { -e $src . $_ } @$files);
    #- cpio -pldm won't copy recursively, use rsync -r instead
    system('rsync', '-ar', '--files-from=' . $list_file, '--link-dest=' . $src, $src, $dest);
    unlink $list_file;
    chdir($pwd);
}

sub list_loopback_modules {
    my ($live) = @_;
    map {
        my $l = $_;
        map {
            my $list = $_;
            my $name = basename($list);
            $name =~ s/\.[^.]+$//;
            { type => $l->{type}, name => $name, files => [ expand_file_list($live, { source => $list }) ] };
        } glob(($_->{rooted} && $live->get_system_root) . $_->{source});
    } @{$live->{loopbacks}{modules}};
}

sub create_loopback_files {
    my ($live) = @_;
    # umount filesystem in the live before creating the loopback
    umount_external_filesystem($live);

    my @excluded_files = expand_file_list($live, @{$live->{loopbacks}{exclude}{files} || []});
    my @modules_files = expand_file_list($live, @{$live->{loopbacks}{modules} || []});

    foreach (grep { exists $loop_types{$_->{type}}{build} } @{$live->{mount}{dirs} || []}) {
        local $_->{exclude} = [ @excluded_files, @modules_files ];
        $loop_types{$_->{type}}{build}->($live, $_);
    }

    foreach my $module (list_loopback_modules($live)) {
        my $copy_tree = $live->get_system_root . "/tmp/draklive/loop/$module->{name}";
        eval { rm_rf($copy_tree) };
        hardlink_filtered($live->get_system_root, $copy_tree, $module->{files});
        my $loop = $loop_types{$module->{type}};
        $loop->{build}->($live, { path => "$live->{prefix}{build}{modules}/$module->{name}", root => $copy_tree, exclude => \@excluded_files });
        eval { rm_rf($copy_tree) };
    }

    if (@excluded_files) {
        my $excluded_tree = $live->get_system_root . "/tmp/draklive/excluded/all";
        eval { rm_rf($excluded_tree) };
        hardlink_filtered($live->get_system_root, $excluded_tree, \@excluded_files);

        foreach my $module (list_loopback_modules($live)) {
            my $copy_tree = $live->get_system_root . "/tmp/draklive/excluded/$module->{name}";
            eval { rm_rf($copy_tree) };
            hardlink_filtered($excluded_tree, $copy_tree, $module->{files});
            my $loop = $loop_types{$module->{type}};
            $loop->{build}->($live, { path => "$live->{prefix}{build}{modules}/excluded-$module->{name}", root => $copy_tree });
            eval { rm_rf($copy_tree) };
        }

        my $loop = $loop_types{$live->{loopbacks}{exclude}{type}};
        $loop->{build}->($live, { path => "/excluded", root => $excluded_tree, exclude => \@modules_files });

        eval { rm_rf($excluded_tree) };
    }
}

sub list_selected_loopbacks {
    my ($live) = @_;
    my @pack = $live->{settings}{pack} ? @{$live->{packs}{$live->{settings}{pack}} || []} : ();
    my @pack_modules = grep { member($_->{name}, @pack) } list_loopback_modules($live);
    (map { $loop_types{$_->{type}}{is_loopback} && $_->{path} ? $_->{path} . $loop_types{$_->{type}}{extension} : () } @{$live->{mount}{dirs} || []}),
    (map { $live->{prefix}{build}{modules} . '/' . $_->{name} . $loop_types{$_->{type}}{extension} } @pack_modules);
}

sub get_media_device {
    my ($live, $opts) = @_;
    return $opts->{device} if $opts->{device};
    my $label = $live->{media}->get_media_label or return $live->{media}->get_media_setting('source');
    my $device = chomp_(`readlink -f /dev/disk/by-label/$label`)
      or die "unable to find device for /dev/disk/by-label/$label\n";
    $device;
}

sub prepare_bootloader {
    my ($live) = @_;
    create_initrd($live);
    create_bootloader($live);
}

sub create_initrd {
    my ($live) = @_;
    if (need_media_specific_boot($live)) {
        MDV::Draklive::Initrd::create_media_initrd($live);
    } else {
        MDV::Draklive::Initrd::create_classical_initrd($live);
    }
}

sub create_bootloader {
    my ($live) = @_;
    if (need_media_specific_boot($live)) {
        create_media_bootloader($live);
    } else {
        create_classical_bootloader($live);
    }

    run_({ root => $live->get_system_root }, '/usr/sbin/grub-gfxmenu', '--update-gfxmenu');
    my $boot_dir = $live->get_builddir . $live->{prefix}{build}{boot};
    mkdir_p($boot_dir);
    my $gfxmenu = $live->get_system_root . '/boot/gfxmenu';
    if (-e $gfxmenu) {
        cp_f($gfxmenu, $boot_dir);
    } else {
        warn "no gfxmenu file\n";
    }
}

sub remove_unneeded_bootlogo_locales {
    use File::Temp;
    use Cwd;

    my ($bootlogo, @locales) = @_;

    $bootlogo = Cwd::realpath($bootlogo);
    -f $bootlogo or return;

    my $cwd = Cwd::getcwd();
    my $tempdir = File::Temp::tempdir("mdvgfxbootXXXX", CLEANUP => 1);
    chdir $tempdir;
    !system("cpio -id < $bootlogo") or return;

    # Make sure we include the en locale
    push @locales, 'en';
    my @kept_locales;
    foreach my $file (glob "*.tr") {
        if (!any { $file =~ /^$_\.tr$/ } @locales) {
            unlink $file;
        } else {
	    my ($locale_name) = $file =~ /(.*)\.tr$/;
	    push @kept_locales, $locale_name;
        }
    }
    system(qq(echo init 16x16.fnt *.tr |sed "s/ /\\n/g" |cpio -o >$bootlogo));
    chdir $cwd;

    print "gfxboot locales: " . join(" ", @kept_locales) . "\n";
    return @kept_locales;
}

sub create_media_bootloader {
    my ($live) = @_;
    cp_f($live->get_system_root . '/boot/vmlinuz-' . $live->find_kernel, $live->get_builddir . $live->{prefix}{build}{boot} . '/vmlinuz');
    require bootsplash;
    my $theme = do {
        local $::prefix = $live->get_system_root;
        bootsplash::themes_read_sysconfig('800x600');
    };
    my $syslinux_dir = $live->get_builddir . $live->{prefix}{build}{boot} . '/syslinux';
    mkdir_p($syslinux_dir);
    my $default_gfxboot_theme = "Mandriva";
    print "copying $default_gfxboot_theme gfxboot theme\n";
    cp_f(glob_($live->get_system_root . "/usr/share/gfxboot/themes/$default_gfxboot_theme/install/*"), $syslinux_dir);
    if ($theme->{name} ne $default_gfxboot_theme) {
        print "copying $theme->{name} gfxboot theme\n";
        cp_f(glob_($live->get_system_root . "/usr/share/gfxboot/themes/$theme->{name}/*"), $syslinux_dir);
    }
    my $bootlogo = $syslinux_dir . '/bootlogo';
    warn "unable to find gfxboot splash ($bootlogo)\n" if ! -f $bootlogo;
    my @locales = remove_unneeded_bootlogo_locales($bootlogo, get_langs($live));
    output_p($syslinux_dir . '/langs', join("\n", @locales) . "\n");
    output_p($syslinux_dir . '/gfxboot.cfg', join("\n", "livecd=1", "mainmenu.pos=210,235",
	                                          "mainmenu.bar.minwidth=400", "panel.f-key.fg=0x33358c"));

    output($live->get_builddir . $live->{prefix}{build}{boot} . '/help.msg',
           pack("C*", 0x0E, 0x80, 0x03, 0x00, 0xC) . qq(
Welcome to Mandriva live!

The command line can be used to specify kernel options.

$live->{media}{title} <kernel options>

));

    foreach my $boot ('', @{$live->{media}{extra_boot}}) {
        my $opts = { boot => $boot };
        output($live->get_builddir . $live->{prefix}{build}{boot} . get_syslinux_path($live->{media}, $opts),
               build_syslinux_cfg($live, $live->{media}, $opts));
    }
}

sub create_classical_bootloader {
    my ($live) = @_;
    my $initrd_prefix = "/initrd.img";
    my $initrd = $live->get_system_root . $live->get_media_prefix('boot') . $initrd_prefix;
    my $part_idx = $live->{media}->find_boot_partition_index;
    my $oem_rescue_idx = $live->{media}->find_partition_index('OEM_RESCUE');
    output_p($live->get_system_root . '/boot/grub/menu.lst', build_grub_cfg_raw($live, $live->{media}, -e $initrd && $initrd_prefix, { oem_rescue_idx => $oem_rescue_idx }, $part_idx));
}

sub set_device_label {
    my ($device, $type, $label) = @_;
    if ($type eq 'vfat') {
        MDV::Draklive::Utils::mtools_run_('mlabel', '-i', $device, '::' . $label);
    } elsif (member($type, 'ext2', 'ext3')) {
        run_('e2label', $device, $label);
    } else {
        die "unable to set label for unsupported media type $type\n";
    }
}

sub get_cdrom_master_path {
    my ($live, $opts) = @_;
    $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . ($opts->{boot} && "-boot-$opts->{boot}") . '.iso';
}

sub create_cdrom_master {
    my ($live, $opts) = @_;
    my $label = $live->{media}->get_media_label or die "the source device must be described by a label\n";
    my $dest;
    unless ($opts->{onthefly}) {
        $dest = get_cdrom_master_path($live, $opts);
        mkdir_p(dirname($dest));
    }
    build_iso_image(
        $dest,
        $live->get_builddir . $live->{prefix}{build}{boot} . '/syslinux',
        $live->get_builddir . $live->{prefix}{build}{boot} . get_syslinux_path($live->{media}, $opts),
        $label,
        $live->get_media_prefix('boot', $opts->{boot}) . '=' . $live->get_builddir . $live->{prefix}{build}{boot},
        if_(!$opts->{boot_only},
            (map {
                 $live->get_media_prefix('loopbacks', $opts->{boot}) . $_ .
                 '=' .
                 $live->get_builddir . $live->{prefix}{build}{loopbacks} . $_;
             } list_selected_loopbacks($live)),
             if_($live->{media}{files},
                map { 
                    $_ . '=' . $live->get_builddir . $live->{prefix}{build}{files} . '/' . $_;
                } all($live->get_builddir . $live->{prefix}{build}{files})
             ),
        ),
    );
}

sub build_iso_image {
    my ($dest, $o_isolinux_path, $isolinux_cfg, $label, @opts) = @_;

    my $progress = MDV::Draklive::Progress->new(100, time());
    my $in_progress;
    autoflush STDOUT 1;
    run_foreach(sub {
                    if (/^\s*([0-9.]+)%\s*done,/) {
                        $progress->{current} = int($1);
                        $progress->show(time());
                        $in_progress = 1;
                    } else {
                        print "\n" if $in_progress;
                        print $_;
                        $in_progress = 0;
                    }
                },
         'genisoimage', '-pad', '-l', '-R', '-J',
         '-V', $label, #'-A', $application, '-p', $preparer, '-P', $publisher,
         '-b', 'isolinux/isolinux.bin',
         '-c', 'isolinux/boot.cat',
         '-hide-rr-moved', '-no-emul-boot',
         '-boot-load-size', 4, '-boot-info-table',
         '-graft-points',
         if_($dest, '-o', $dest),
         if_($o_isolinux_path, 'isolinux=' . $o_isolinux_path),
         'isolinux/isolinux.cfg=' . $isolinux_cfg,
         'isolinux/isolinux.bin=/usr/lib/syslinux/isolinux.bin',
         'isolinux/gfxboot.com=/usr/lib/syslinux/gfxboot.com',
         @opts,
    ) or die "unable to run genisoimage\n";
    autoflush STDOUT 0;
    $progress->end;
    if ($dest) {
        my $dir = dirname($dest);
        my $filename = basename($dest);
        run_('isohybrid', $dest);
        run_('mkcd', '>', '/dev/null', '2>', '/dev/null', '--addmd5', $dest);
        run_({ chdir => $dir }, 'md5sum', '>', $dest . '.md5', $filename);
        run_({ chdir => $dir }, 'sha1sum', '>', $dest . '.sha1', $filename);
    }
}

sub get_disk_master_path {
    my ($live) = @_;
    $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . '.img';
}

sub allocate_partition {
    my ($dest, $part_idx, $fs, $o_inode_size) = @_;
    my @parts = group_by2(run_program::get_stdout("sfdisk -d $dest") =~ /start=\s*(\d+),\s*size=\s*(\d+)/g);
    my ($part_start, $part_nb_sectors) = @{$parts[$part_idx]};

    require devices;
    my $loop = devices::find_free_loop();
    run_('losetup', '-o', $part_start * $common::SECTORSIZE, '-s', $part_nb_sectors * $common::SECTORSIZE, $loop, $dest)
      or die "unable to setup loop device";
    MDV::Draklive::Utils::device_mkfs($loop, $fs, $o_inode_size) or die "unable to format $dest\n";

    return $loop;
}

sub allocate_master {
    my ($live, $media, $dest) = @_;

    my $geom = $media->{geom} || {
        heads => 16,
        sectors => 63, # sectors per track
    };

    my $disk_sectors = fold_left { $::a + $::b } map { $_->{size} } @{$live->{media}{partitions}};
    $disk_sectors += $geom->{sectors}; # keep one more track
    $geom->{cylinders} = int($disk_sectors / ($geom->{sectors} * $geom->{heads}));

    mkdir_p(dirname($dest));
    MDV::Draklive::Utils::device_allocate_file($dest, $disk_sectors * $common::SECTORSIZE);

    my $hd = bless {
        totalsectors => $geom->{cylinders} * $geom->{heads} * $geom->{sectors},
        geom => $geom,
        file => $dest,
    }, 'partition_table::dos';

    partition_table::raw::zero_MBR($hd);

    #- FIXME: maybe use fsedit::allocatePartitions to factorize even more?
    foreach my $part (@{$media->{partitions}}) {
        my $hole = find { fs::type::isEmpty($_) && $_->{size} >= $part->{size} } partition_table::get_normal_parts_and_holes($hd)
          or die "not enough room for $part->{mntpoint}";
        $part->{start} = $hole->{start};
        fs::type::set_fs_type($part, $part->{fs_type});
        partition_table::add($hd, $part, 'Primary');
    }

    partition_table::write($hd);

    my $inode_size = $media->get_media_setting('inode_size');
    map_index { allocate_partition($dest, $::i, $_->{fs_type}, $inode_size) } @{$media->{partitions}};
}

sub create_disk_master {
    my ($live, $opts) = @_;

    my $slash_size = @{$live->{mount}{dirs} || []} ?
      (directory_usage($live->get_builddir . $live->{prefix}{build}{loopbacks}) +
       directory_usage($live->get_builddir . $live->{prefix}{build}{boot}) +
       directory_usage($live->get_builddir . $live->{prefix}{build}{files})
      ) :
      directory_usage($live->get_system_root);

    $live->{media}->supplement_partitions($slash_size);

    my $dest = get_disk_master_path($live);
    my @loops = allocate_master($live, $live->{media}, $dest);
    my $slash_idx = $live->{media}->find_partition_index('/');
    local $opts->{device} = $loops[$slash_idx];
    local $opts->{disk_device} = $dest;
    record_master($live, $opts);
    my $oem_rescue_idx = $live->{media}->find_partition_index('OEM_RESCUE');
    if (defined $oem_rescue_idx) {
        record_oem_rescue($live, $loops[$oem_rescue_idx], $opts);
    }
    run_('losetup', '-d', $_) foreach @loops;
}

#- $opts:
#-   media: alternate media
#-   onthefly : if true, the create function must output to stdout
sub create_master {
    my ($live, $opts) = @_;

    if (my $create = $live->{media}->get_boot_setting('create', $opts)) {
        $create->($live, $opts);
    } else {
        warn "not implemented yet\n";
    }
}

sub maybe_umount_device {
    my ($device) = @_;
    run_('umount', $device) if cat_('/proc/mounts') =~ m!^$device\s+!m;
}

sub format_cdrom_device {
    my ($live, $opts) = @_;
    run_('wodim', '-v', 'dev=' . get_media_device($live, $opts), "blank=fast");
}

sub format_usb_device {
    my ($live, $opts) = @_;
    my $device = get_media_device($live, $opts);
    maybe_umount_device($device);
    MDV::Draklive::Utils::device_mkfs($device, $live->{media}->get_media_setting('fs'), $live->{media}->get_media_setting('inode_size'))
      or die "unable to format device $device\n";
}

#- $opts:
#-   media: alternate media
sub format_device {
    my ($live, $opts) = @_;

    get_media_device($live, $opts) or die "no device defined in media configuration\n";
    if (my $format = $live->{media}->get_boot_setting('format', $opts)) {
        $format->($live, $opts);
    } else {
        warn "not implemented yet\n";
    }
}

sub record_cdrom_master {
    my ($live, $opts) = @_;
    my $device = get_media_device($live, $opts)
      or die "no device defined in media configuration\n";
    my $src = $opts->{onthefly} ? '-' : get_cdrom_master_path($live, $opts);
    run_('wodim', '-v', 'dev=' . $device, $src);
}

sub install_grub_to_image {
    my ($live, $media, $img) = @_;
    my $grub_dir = "/boot/grub";
    my $grub_script = $grub_dir . "/install.sh";
    mkdir_p($live->{mnt} . $grub_dir);
    cp_af(glob_($live->get_system_root . "/lib/grub/i386-mandriva/*"), $live->{mnt} . $grub_dir);

    my $part_idx = $media->find_boot_partition_index;

    open(my $grub, "| /sbin/grub --batch --no-floppy");
    # using disk loopback fails, have to use image path
    print $grub <<EOF;
device (hd0) $img
root (hd0,$part_idx)
setup (hd0)
quit
EOF
    close($grub) or die "unable to run grub\n";

    output($live->{mnt} . $grub_script, <<EOG);
grub --device-map=/boot/grub/device.map --batch <<EOF
root (hd0,$part_idx)
setup --stage2=/boot/grub/stage2 (hd0)
quit
EOF
EOG

    chmod 0755, $live->{mnt} . $grub_script;
}

sub install_usb_bootloader {
    my ($live, $media, $opts) = @_;
    my $media_boot = $live->get_media_prefix('boot', $opts->{boot});
    my $device = get_media_device($live, $opts);
    my $bootloader = $media->get_boot_setting('bootloader', $opts);

    member($bootloader, 'grub', 'syslinux') or die "no bootloader defined in media configuration\n";
    if ($bootloader eq 'syslinux') {
        cp_f($live->get_builddir . $_, $live->{mnt}) foreach map {
            $live->{prefix}{boot} . $_;
        } get_syslinux_path($media, $opts), $media->get_initrd_path, @syslinux_boot_files;
    } elsif ($bootloader eq 'grub') {
        #- FIXME: add get_grub_path (when building boot configuration files)
        #         and get_bootloader_path (when copying)
        mkdir_p($live->{mnt} . $media_boot . '/grub');
        cp_f($live->get_builddir . $live->{prefix}{build}{boot} . '/gfxmenu', $live->{mnt} . $media_boot);
        output_p($live->{mnt} . $media_boot . '/grub/menu.lst', build_grub_cfg($live, $media, $opts, $device));
    }

    if (-b $device) {
        if ($bootloader eq 'syslinux') {
            #- use syslinux -s, "safe, slow and stupid" version of SYSLINUX, unless specified otherwise
            run_('syslinux', if_(!$media->{fast_syslinux}, '-s'), $device)
              or die "unable to run syslinux on $device\n";
        } elsif ($bootloader eq 'grub') {
            my $master_device = $opts->{disk_device};
            if (!$master_device) {
                $master_device = $device;
                $master_device =~ s/(\d+)$//;
            }
            if ($master_device =~ m!/dev/!) {
                my $local_grub_install = $live->get_builddir . $live->{prefix}{build}{scripts} . '/grub-install';
                mkdir_p(dirname($local_grub_install));
                cp_f($live->get_system_root . '/sbin/grub-install', $local_grub_install);
                my $root = $live->get_system_root;
                #- FIXME: use a grub/install.sh script?
                substInFile {
                    s!^\s*exec_prefix=.*!exec_prefix=$root!;
                    s!^\s*grub_prefix=/boot/!grub_prefix=${media_boot}/!;
                    s!^\s*bootdir=(.*)/boot$!bootdir=$1${media_boot}!;
                } $local_grub_install;
                my $grub_device_map = $live->{mnt} . $media_boot . "/grub/device.map";
                unlink $grub_device_map;
                foreach ($master_device, $device) {
                    run_($local_grub_install, '--root-directory=' . $live->{mnt}, '--no-floppy', $_)
                      or die "unable to run grub on $device\n";
                }
                unlink $grub_device_map;
            } else {
                install_grub_to_image($live, $media, $master_device);
            }
        }
    } else {
        warn "not running $bootloader on non block device $device\n";
    }
}

sub record_usb_master {
    my ($live, $opts) = @_;
    my $media = $live->{media};
    my $media_boot = $live->get_media_prefix('boot', $opts->{boot});
    my $media_loopbacks = $live->get_media_prefix('loopbacks', $opts->{boot});

    if (my $label = !$opts->{boot_only} && $opts->{device} && $media->get_media_label) {
        set_device_label($opts->{device}, $media->get_media_setting('fs'), $label);
    }
    my $device = get_media_device($live, $opts)
      or die "unable to find recording device (missing label? try with --device <device>)\n";

    mkdir_p($live->{mnt});
    run_('mount', if_(-f $device, '-o', 'loop'), $device, $live->{mnt})
      or die "unable to mount $device\n";
    rm_rf($live->{mnt} . $media_boot) if -e $live->{mnt} . $media_boot;
    cp_af($live->get_builddir . $live->{prefix}{build}{boot}, $live->{mnt} . $media_boot);

    install_usb_bootloader($live, $media, $opts);

    do {
        my $loopbacks_source = $live->get_builddir . $live->{prefix}{build}{loopbacks} . '/';
        my $total = directory_usage($loopbacks_source);
        my $list_file = tmpnam();
        output_p($list_file, map { ".$_\n" } list_selected_loopbacks($live));
        local $/ = "\r";
        my $r = run_foreach(update_progress_rsync($live, $total),
                            'rsync', '-vdP', '--inplace', '--files-from=' . $list_file,
                            $loopbacks_source, $live->{mnt} . $media_loopbacks,
        );
        unlink $list_file;
        if (!$r) {
            run_('umount', $live->{mnt});
            maybe_umount_device($device);
            die "unable to copy loopback files\n";
        }

        cp_af(glob_($live->get_builddir . $live->{prefix}{build}{files} . '/*'), $live->{mnt});
    } unless $opts->{boot_only};

    my @hidden_files = map { basename($_) } glob_($live->{mnt} . "/.*"), glob_($live->{mnt} . "/autorun.*");

    run_('umount', $live->{mnt});
    maybe_umount_device($device);

    if ($media->get_media_setting('fs') eq 'vfat') {
        MDV::Draklive::Utils::mtools_run_('mattrib', '+h', '-i', $device, '::' . $_) foreach @hidden_files;
        MDV::Draklive::Utils::mtools_run_('mattrib', '+r', '+s', '-/', '-i', $device, '::' . $_)
          foreach $media_boot, $media_loopbacks;
    }
}

sub record_harddisk_master {
    my ($live, $opts) = @_;
    my $media = $live->{media};
    my $media_boot = $live->get_media_prefix('boot', $opts->{boot});
    my $media_loopbacks = $live->get_media_prefix('loopbacks', $opts->{boot});

    if (my $label = !$opts->{boot_only} && $opts->{device} && $media->get_media_label) {
        set_device_label($opts->{device}, $media->get_media_setting('fs'), $label);
    }
    my $device = get_media_device($live, $opts)
      or die "unable to find recording device (missing label? try with --device <device>)\n";

    mkdir_p($live->{mnt});
    run_('mount', if_(-f $device, '-o', 'loop'), $device, $live->{mnt})
      or die "unable to mount $device\n";

    do {
        my $source = $live->get_system_root;
        my $total = directory_usage($source);
        local $/ = "\r";
        my $r = run_foreach(update_progress_rsync($live, $total), 'rsync', '-a', $source . '/', $live->{mnt});
        if (!$r) {
            run_('umount', $live->{mnt});
            maybe_umount_device($device);
            die "unable to copy system files\n";
        }
    } unless $opts->{boot_only};

    install_grub_to_image($live, $media, $opts->{disk_device});

    run_('umount', $live->{mnt});
    maybe_umount_device($device);
}

#- $opts:
#-   onthefly : if true, the record function must read from stdin
sub record_master {
    my ($live, $opts) = @_;

    if (my $record = $live->{media}->get_boot_setting('record', $opts)) {
        $record->($live, $opts);
    } else {
        warn "not implemented yet\n";
    }
}

sub pipe_subs {
    my ($writer, $reader) = @_;
    my ($r, $w) = POSIX::pipe;
    if (my $pid = fork()) {
        POSIX::close($w) or die "couldn't close: $!\n";
        my $stdin = POSIX::dup(0) or die "couldn't dup: $!\n";
        POSIX::dup2($r, 0) or die "couldn't dup2: $!\n";
        POSIX::close($r);
        $reader->();
        POSIX::close(0) or warn "writer exited $?\n";
        POSIX::dup2($stdin, 0) or die "couldn't dup2: $!\n";
        waitpid($pid, 0);
    } else {
        POSIX::close($r) or die "couldn't close: $!\n";
        #- don't screw up reader
        POSIX::dup2(POSIX::open('/dev/null', &POSIX::O_WRONLY), 2) or die "couldn't dup2: $!\n";
        POSIX::dup2($w, 1) or die "couldn't dup2: $!\n";
        POSIX::close($w);
        $| = 1; #- autoflush write
        exit !$writer->();
    }
}

sub record_onthefly {
    my ($live, $opts) = @_;

    my $record = $live->{media}->get_storage_setting('record');
    unless ($record) {
        warn "not implemented yet\n";
        return;
    }
    if (my $create = $live->{media}->get_storage_setting('record_needs_master') && $live->{media}->get_storage_setting('create')) {
        local $opts->{onthefly} = 1;
        #- pipe creation step to recording step
        pipe_subs(sub { $create->($live, $opts) },
                  sub { $record->($live, $opts) });
    } else {
        #- no creation step, record directly
        $record->($live, $opts);
    }
}

sub need_compressed_image {
    my ($live) = @_;
    #- compress image if not having loopbacks already
    !to_bool(list_selected_loopbacks($live));
}

sub get_disk_image_path {
    my ($live) = @_;
    get_disk_master_path($live) . if_(need_compressed_image($live), '.bz2');
}

sub create_disk_image {
    my ($live) = @_;
    if (!need_compressed_image($live)) {
        warn "already using loopback: skipping image creation\n";
        return;
    }
    my $master = get_disk_master_path($live);
    my $dest = get_disk_image_path($live);
    mkdir_p(dirname($dest));
    run_('bzip2', '>', $dest, '-f', '-k', '-c', $master);
}

sub create_image {
    my ($live) = @_;

    if (my $create = $live->{media}->get_media_setting('image')) {
        $create->($live);
    } else {
        warn "not implemented yet\n";
    }
}

sub get_rescue_files {
    my ($live, $rescue_opts, $extra_files) = @_;
    my $media_boot = $live->get_media_prefix('boot');
    my $initrd = $media_boot . $rescue_opts->{media}->get_initrd_path;
    (
        '/usr/lib/drakx-installer-images/isolinux/alt0/vmlinuz' => $media_boot . '/vmlinuz',
        '/usr/lib/drakx-installer-images/isolinux/alt0/all.rdz' => $initrd,
        '/usr/lib/drakx-installer-rescue/rescue.sqfs' => '/install/stage2/',
        @{$extra_files || []},
        #- FIXME: factorize with copy_files_to to handle glob
        (map { $live->{settings}{config_root} . '/' . $_->[0] => '/' . $_->[1] } @{$rescue_opts->{files} || []}),
    );
}

sub record_rescue_files {
    my ($mnt, $device, $rescue_files) = @_;
    my $failed;
    foreach (group_by2(@$rescue_files)) {
        my ($src, $dest) = @$_;
        $dest = $mnt . $dest;
        mkdir_p($dest =~ m!/$! ? $dest : dirname($dest));
        if (!run_('rsync', '-vdP', '--inplace', $src, $dest)) {
            $failed = 1;
            last;
        }
    }

    #- FIXME
    chmod 0755, $mnt . '/' . 'oem-rescue.sh';

    if ($failed) {
        run_('umount', $mnt);
        maybe_umount_device($device);
        die "unable to copy rescue files\n";
    }
}

sub record_oem_rescue {
    my ($live, $device, $opts) = @_;
    my $media = $live->{oem_rescue}{media};
    my $media_boot = $live->get_media_prefix('boot');
    mkdir_p($live->{mnt});
    run_('mount', if_(-f $device, '-o', 'loop'), $device, $live->{mnt})
      or die "unable to mount $device\n";

    record_rescue_files($live->{mnt}, $device, [ get_rescue_files($live, $live->{oem_rescue}) ]);

    run_('umount', $live->{mnt});
    maybe_umount_device($device);
}

sub get_disk_replicator_path {
    my ($live) = @_;
    $live->get_builddir . $live->{prefix}{build}{dist} . '/' . $live->get_name . '.rest.img';
}

sub get_disk_replicator_files {
    my ($live) = @_;
    get_rescue_files($live, $live->{replicator}, [ get_disk_image_path($live) => '/images/' ]);
}

sub create_usb_replicator {
    my ($live) = @_;
    my $dest = get_disk_replicator_path($live);
    my %files = get_disk_replicator_files($live);

    my $size = fold_left { $::a + $::b } map { directory_usage($_, 'apparent') } keys(%files);
    $live->{replicator}{media}->supplement_partitions($size);

    my @loops = allocate_master($live, $live->{replicator}{media}, $dest);
    my $slash_idx = $live->{replicator}{media}->find_partition_index('/');
    my $opts = { device => $loops[$slash_idx], disk_device => $dest, append => $live->{replicator}{append} };
    record_usb_replicator($live, $opts);
    run_('losetup', '-d', $_) foreach @loops;
}

sub record_usb_replicator {
    my ($live, $opts) = @_;
    my $media = $live->{replicator}{media};
    my $media_boot = $live->get_media_prefix('boot');
    my $device = get_media_device($live, $opts)
      or die "unable to find recording device (missing label? try with --device <device>)\n";
    mkdir_p($live->{mnt});
    run_('mount', if_(-f $device, '-o', 'loop'), $device, $live->{mnt})
      or die "unable to mount $device\n";
    rm_rf($live->{mnt} . $media_boot) if -e $live->{mnt} . $media_boot;
    install_usb_bootloader($live, $media, $opts);

    record_rescue_files($live->{mnt}, $device, [ get_disk_replicator_files($live) ]);
    output_p($live->{mnt} . "/images/list", "EN,English," . basename(get_disk_image_path($live)) . ",on\n");

    run_('umount', $live->{mnt});
    maybe_umount_device($device);
}

sub create_cdrom_replicator {
    my ($live, $opts) = @_;

    # FIXME: factorize with usb replicator, write in builddir/replicator/images-list
    my $images_list = "/tmp/images-replicator.list";
    output_p($images_list, "EN,English," . basename(get_disk_image_path($live)) . ",on\n");

    # FIXME: write in builddir/replicator/syslinux.cfg
    my $syslinux_cfg = "/tmp/syslinux-replicator.cfg";
    local $opts->{append} = $live->{replicator}{append};
    output_p($syslinux_cfg, build_syslinux_cfg($live, $live->{replicator}{media}, $opts));

    my $label = $live->{replicator}{media}->get_media_label or die "the source device must be described by a label\n";
    my $dest = get_disk_replicator_path($live);
    $dest =~ s/.img$/.iso/;
    build_iso_image(
        $dest,
        '',
        $syslinux_cfg,
        $label,
        "/images/list=$images_list",
        (map {
            my ($src, $dest) = @$_;
            my $dest_file = $dest =~ m!/$! ? $dest . basename($src) : $dest;
            $dest_file . "=" . $src;
        } group_by2(get_disk_replicator_files($live))),
    );
}

sub create_replicator {
    my ($live) = @_;

    if (my $create = $live->{replicator}{media} && $live->{replicator}{media}->get_media_setting('replicator')) {
        $create->($live);
    } else {
        warn "not implemented yet\n";
    }
}

sub update_progress_rsync {
    my ($live, $total) = @_;
    my $all_files = 0;
    my $current_file = 0;
    $live->{update_progress} ? sub {
        if (/^\s*(\d+)\s+\d+%\s+/) {
            $current_file = $1;
            $live->{update_progress}->(undef, $all_files + $current_file, $total);
        }
        if (/(?:^|\n)\S+/) {
            $all_files += $current_file;
            $current_file = 0;
        }
    } : sub { print };
}

sub copy_wizard {
    my ($live) = @_;

    MDV::Draklive::Config::complete_config($live);
    $live->{system}{vga_mode} = 788 if !defined $live->{system}{vga_mode};
    my $live_media = $live->{prefix}{live}{mnt} . $live->{prefix}{media}{mnt};

    require interactive;
    require wizards;
    my $in = 'interactive'->vnew('su');
    my (@available_storage, @available_devices);
    my ($storage, $device, $format);
    my %source_types = (
        live => N("Use current live system"),
        file => N("Select a file"),
    );
    my ($source_type, $source_path);
    my $media_boot = $live->get_media_prefix('boot');
    my $media_loopbacks = $live->get_media_prefix('loopbacks');
    my $source_is_mounted = sub { -d ($live->{settings}{builddir} . $media_boot) };
    my $umount_source = sub {
        if ($source_type ne 'live' && $source_is_mounted->()) {
            run_('umount', $live->{settings}{builddir});
            rmdir($live->{settings}{builddir});
        }
    };
    my $w;
    $w = wizards->new({
        name => N("Live system copy wizard"),
        pages => {
            welcome => {
                name => N("Welcome to the live system copy wizard"),
                no_back => 1,
                next => 'source',
            },
            source => {
                name => N("Which live system do you want to copy?"),
                data => [ if_(-d ($live_media . $media_loopbacks),
                              { type => 'list', val => \$source_type,
                                list => sort(keys(%source_types)),
                                format => sub { $source_types{$_[0]} } }),
                          { type => 'file', val => \$source_path,
                            disabled => sub { $source_type eq 'live' } } ],
                pre => $umount_source,
                complete => sub {
                    if ($source_type eq 'live') {
                        $live->{settings}{builddir} = $live_media;
                    } else {
                        $live->{settings}{builddir} = File::Temp::tempdir();
                        if (!run_('mount', '-o', 'loop', $source_path, $live->{settings}{builddir})) {
                            $in->ask_warn(N("Error"), N("Unable to use selected file"));
                            return 1;
                        }
                    }
                    0;
                },
                post => sub {
                    my $boot = $live->{settings}{builddir} . $media_boot;
                    @available_storage = sort(grep { -d "$boot/$_" && exists $MDV::Draklive::Storage::storage_types{$_}{detect} } all($boot));
                    if (@available_storage == 1) {
                        $storage = $available_storage[0];
                        return 'device';
                    }
                    return 'storage';
                }
            },
            storage => {
                name => N("Please select the medium type"),
                data => [ { type => 'list', allow_empty_list => 1,
                            val => \$storage, list => \@available_storage } ],
                next => 'device',
            },
            device => {
                name => N("Please select the device that will contain the new live system"),
                pre => sub {
                    my %devices = map { $_->{device} => $_ } $MDV::Draklive::Storage::storage_types{$storage}{detect}->();
                    $_->{formatted_name} = $_->{usb_description} || $_->{info} || $_->{device} foreach values %devices;
                    @available_devices = ();
                    require fs::proc_partitions;
                    foreach (fs::proc_partitions::read([ values %devices ])) {
                        if ($_->{rootDevice} && exists $devices{$_->{rootDevice}}) {
                            my $description = $devices{$_->{rootDevice}}{usb_description} || $devices{$_->{rootDevice}}{info};
                            $_->{formatted_name} = $description ? "$description ($_->{device})" : $_->{device};
                            push @available_devices, $_;
                        }
                    }
                    delete $devices{$_->{rootDevice}} foreach @available_devices;
                    unshift @available_devices, map { $devices{$_} } sort keys %devices;
                    undef $device;
                },
                data => [ { type => 'list', allow_empty_list => 1,
                            val => \$device, , list => \@available_devices,
                            format => sub { $_[0]{formatted_name} } },
                          { text => N("Format selected device"), val => \$format, type => 'bool' } ],
                complete => sub {
                    return 0 if defined $device;
                    $in->ask_warn(N("Error"), N("You must select a device!"));
                    1;
                },
                post => sub {
                    (my $_wait, $live->{update_progress}) = $in->wait_message_with_progress_bar;
                    do {
                        local $::isInstall = 1; # quick hack to embed the wait message
                        $live->{update_progress}->(N("Copying in progress"));
                    };
                    eval {
                        my $opts = { media => { storage => $storage, device => '/dev/' . $device->{device} } };
                        format_device($live, $opts) if $format;
                        record_onthefly($live, $opts);
                    };
                    delete $live->{update_progress};
                    if (my $error = $@) {
                        $in->ask_warn(N("Error"), $error);
                        $w->{pages}{device}{end} = 1;
                    }
                    return "end";
                },
            },
            end => {
                name => N("Congratulations") . "\n\n" . N("Your live system is now copied."),
                no_back => 1,
                end => 1,
            },
        }
    });
    $w->process($in);
    $umount_source->();
    $in->exit;
}

sub clean {
    my ($live) = @_;
    # umount filesystem in the live before cleaning
    umount_external_filesystem($live);
    rm_rf($_) foreach grep { -e $_ } $live->get_builddir, $live->get_system_root;
}

my @actions = (
    { name => 'dump-config', do => \&MDV::Draklive::Config::dump_config },
    { name => 'clean', do => \&clean },
    { name => 'install', do => \&install_system },
    { name => 'post-install', do => \&post_install_system },
    { name => 'initrd', do => \&create_initrd },
    { name => 'boot', do => \&prepare_bootloader },
    { name => 'loop', do => \&create_loopback_files },
    { name => 'master', do => \&create_master },
    { name => 'image', do => \&create_image },
    { name => 'replicator', do => \&create_replicator },
    { name => 'format', do => \&format_device },
    { name => 'record', do => \&record_master },
    { name => 'record-onthefly', do => \&record_onthefly },
);
my @all = qw(install boot loop master image replicator);

die "you must be root to run this program\n" if $>;

my $live_object = 'MDV::Draklive::Live'->new;
my %opts;
my $config_root = $MDV::Draklive::Config::default_config_root;
my $config_path = $MDV::Draklive::Config::default_config_path;
my $settings_path = $MDV::Draklive::Config::default_settings_path;
GetOptions(
    "help" => sub { Pod::Usage::pod2usage('-verbose' => 1) },
    "copy-wizard" => \$live_object->{copy_wizard},
    "boot-only" => \$opts{boot_only},
    "boot-image=s" => sub { $opts{boot} = $_[1]; $opts{boot_only} = 1 },
    "all" => sub { $_->{to_run} = 1 foreach grep { member($_->{name}, @all) } @actions },
    (map { $_->{name} => \$_->{to_run} } @actions),
    "device=s" => sub { $opts{device} = $_[1] },
    "all-regions" => sub { $live_object->{all_regions} = 1 },
    "config-root=s" => \$config_root,
    "config=s" => \$config_path,
    "settings=s" => \$settings_path,
    "define=s" => \%{$live_object->{settings}},
) or Pod::Usage::pod2usage();

require standalone;
if ($live_object->{copy_wizard}) {
    copy_wizard($live_object);
} else {
    every { !$_->{to_run} } @actions and Pod::Usage::pod2usage();
    MDV::Draklive::Config::read_config($live_object, $config_root, $config_path, $settings_path);
    MDV::Draklive::Config::check_config($live_object);
    MDV::Draklive::Config::complete_config($live_object);
    foreach my $region ($live_object->{all_regions} ? sort(keys %{$live_object->{regions}}) : $live_object->{settings}{region}) {
        $region and print qq(=== proceeding with region "$region"\n);
        $live_object->{settings}{region} = $region;
        foreach (grep { $_->{to_run} } @actions) {
            print qq(* entering step "$_->{name}"\n);
            $_->{do}->($live_object, \%opts);
            print qq(* step "$_->{name}" done\n);
        }
    }
}

__END__

=head1 NAME

draklive - A live distribution mastering tool

=head1 SYNOPSIS

draklive [options]

 Options:
   --help            long help message

   --install         install selected distribution in chroot
   --boot            prepare initrd and bootloader files
   --loop            build compressed loopback files
   --master          build master image
   --image           build compressed master image
   --replicator      build replicator image (to dump master on systems)

   --all             run all steps, from installation to mastering

   --clean           clean installation chroot and work directory

   --device <dev>    use this device for live recording (not needed
                     if the device already has the required label)
   --format          format selected device
   --record          record live on selected media
   --record-onthefly record live by creating master from loopback files
                     on the fly

   --initrd          build initrd only
   --post-install    run post install only (rpms and patches installation)

   --config-root <dir>
                     root directory containing config files and additionnal files
                     defaults to current directory if it contains a configuration file
                     else, "/etc/draklive" is used

   --config <file>   use this configuration file as live description
                     defaults to "config/live.cfg"

   --settings <file> use this file as live settings (key=value format)
                     defaults to "config/settings.cfg"
   --define key=value
                     set setting "key" to "value"
                     takes precedence over values from a settings file

   --all-regions     proceed with all configured regions

   --copy-wizard     run the copy wizard

   --boot-only       copy only boot files
                     (affects master/record steps)

   --boot-image <method>
                     create a boot image for the selected method
                     (affects master/record steps, implies --boot-only)

Examples:

 draklive --clean

 draklive --all

 draklive --record --device /dev/sdb1

 draklive --config config/live.cfg --install

=head1 OPTIONS

=over 8

=item B<--config>

Makes draklive use the next argument as a configuration file.
This file should contain an hash describing the live distribution,
meaning the system (chroot and boot), media (usb, cdrom, nfs),
and mount type (simple R/W union, union with squash files).

Here's a configuration sample:

  {
    settings {
        repository => '/mnt/ken/2006.0',
        root => '/chroot/live-move',
    },
    system => {
        kernel => '2.6.12-12mdk-i586-up-1GB',
        auto_install => 'config/auto_inst.cfg.pl',
        patch_install => 'config/patch-2006-live.pl',
        rpmsrate => 'config/rpmsrate',
        rpms => [
             'rpms/unionfs-kernel-2.6.12-12mdk-i586-up-1GB-1.1.1.1.20051124.1mdk-1mdk.i586.rpm'
        ],
        patches => [
             'patches/halt.loopfs.patch',
        ],
        vga_mode => 788,
        no_initrd => 0,
    },
    media => {
        storage => 'cdrom',
    },
    mount => $predefined{mounts}{squash_union}
  };

=item B<--settings>

Makes draklive load the next argument as a file in key=value format
into the $live->{settings} hash ($live being the global live configuration hash).

Built-in keys:
  arch: build architecture
  builddir: directory hosting build files (initrd, loopbacks, images)
  chroot: directory hosting chrooted installations
  region: use the matching set of langs from the regions configuration hash
  repository: path to the Mandriva distribution repository (ftp/http/local)

Example keys:
  desktop
  media
  product

=back

=head1 DESCRIPTION

B<draklive> builds a live distribution according to a
configuration file, creates a master image,
and optionally installs it on a device.

See L<http://qa.mandriva.com/twiki/bin/view/Main/DrakLive>

=head1 AUTHOR

Olivier Blin <oblin@mandriva.com>

=cut