File: linuxrc

package info (click to toggle)
autoinstall 1.0
  • links: PTS
  • area: main
  • in suites: woody
  • size: 356 kB
  • ctags: 41
  • sloc: python: 2,127; perl: 145; sh: 128; makefile: 65
file content (1571 lines) | stat: -rw-r--r-- 53,934 bytes parent folder | download
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
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
#!/usr/bin/python -i

import sys
import os
import popen2
import stat
import traceback
import signal
import string
import time
import copy
import parted

# Arch-specific modules

import partition
import boot

# DebugException class - needed to implement test harness.

class DebugException(Exception):
    pass

# Functions

def runpipe(cmd):
    cmdpipe = os.popen(cmd, "r")
    cmdlines = cmdpipe.readlines()
    cmdresult = cmdpipe.close()
    if cmdresult is not None:
        raise RuntimeError, "Error in executing %s, exit status %d" % (cmd, cmdresult)
    return cmdlines

def runcmd(cmd):
    cmdresult = os.system(cmd)
    if cmdresult != 0:
        raise RuntimeError, "Error in executing %s, exit status %d" % (cmd, cmdresult)

def unmountall():
    mtabinfo = []
    if os.path.exists("/etc/mtab"):
        mtab = open("/etc/mtab")
    else:
        mtab = open("/proc/mounts")
    mtabline = mtab.readline()
    while mtabline:
        mtabfields = string.split(mtabline)
        mtabinfo.append(mtabfields)
        mtabline = mtab.readline()
    mtab.close()

    mtabinfo.reverse()
    for mtabfields in mtabinfo:
        runcmd("umount %s" % mtabfields[1])

def killsystem(msg = "System stopped.  Please reboot."):
    unmountall()

    print msg
    while 1:
        time.sleep(3600)

def default_exception_handler():
    (ex_type, ex_value, ex_tb) = sys.exc_info()

    print \
"""EXCEPTION DETECTED!

An unhandled exception was detected.  Please report the following information in
a bug report to the Debian Bug Tracking System at <submit@bugs.debian.org>;
see /usr/share/doc/debian/bug-reporting.txt for further instructions.

"""

    traceback.print_exception(ex_type, ex_value, ex_tb, None, sys.stdout)

    print \
"""
The autoinstall process will now suspend.  You may try rebooting and running the
autoinstaller again, possibly with different configuration parameters.  If all
else fails, try a conventional installation.
"""

    killsystem()

def exitfunc():
    (type, value, tb) = sys.exc_info()
    if type is not None:
        if type != SystemExit and type != "SystemExit":
            default_exception_handler()

def load_config_lines(modfile):
    "Load config items from a file (one per line) and return them in an array."

    modlist = []
    for cfgline in modfile.readlines():
        cfgline = string.strip(cfgline)
        if cfgline[-1] == "\n":
            cfgline = cfgline[:-1]

        if cfgline not in modlist:
            modlist.append(cfgline)

    return modlist

def load_config_pairs(cfgfile):
    "Load name-value pairs from a file and return them in a dictionary."

    cfglist = {}
    for cfgline in cfgfile.readlines():
        cfgline = string.strip(cfgline)
        if cfgline[-1] == "\n":
            cfgline = cfgline[:-1]

        if len(cfgline) >= 1:
            cfgitems = string.split(cfgline, None, 1)
            if len(cfgitems) == 1:
                cfglist[cfgline] = ""
            else:
                cfglist[cfgitems[0]] = cfgitems[1]

    return cfglist

def load_config_items(cfgfile):
    """Load multivalue groups from a file and return them in an array
       of arrays.  Blank lines translate to empty arrays."""

    cfglist = []
    for cfgline in cfgfile.readlines():
        cfgline = string.strip(cfgline)
        if len(cfgline) < 1:
            cfglist.append([])
            continue

        cfgitems = string.split(cfgline)
        cfglist.append(cfgitems)

    return cfglist

def detect_hardware():
    global netloaded, scsiloaded, netmods, scsimods

    modlist = []
    detect = "scsi ide cdrom ethernet"

    discover = runpipe("discover --module %s" % detect)
    for modline in discover:
        if modline[-1] == "\n":
            modline = modline[:-1]

        modparts = string.split(modline)
        for modpart in modparts:
            modlist.append(modpart)

            if modpart in scsimods:
                print "Loading SCSI module: %s" % modpart
                scsiloaded = 1
                runcmd("modprobe %s" % modpart)
            elif modpart in netmods:
                print "Loading network module: %s" % modpart
                netloaded = 1
                runcmd("modprobe %s" % modpart)
            else:
                print "Module %s detected, but not available - not loading." \
                      % modpart

    # If anything SCSI-related was discovered, load SCSI CD drivers.

    if scsiloaded:
        runcmd("modprobe sr_mod")

# Progeny Debian 1.0 and Debian versions starting with woody have
# different versions of debconf, with different APIs.  We need to make
# that distinction here and call different routines to manipulate
# debconf depending on the version of Debian we're running.

def init_debconf_progeny():
    runcmd("cp /bin/setdebconf /target/tmp")

def set_debconf_progeny(file):
    runcmd("cp %s /target/tmp/debconf-info" % file)
    runcmd("chroot /target /tmp/setdebconf /tmp/debconf-info")
    os.unlink("/target/tmp/debconf-info")

def shutdown_debconf_progeny():
    os.unlink("/target/tmp/setdebconf")

def init_debconf_debian():
    global debconf_comm_process

    debconf_comm_process = popen2.Popen3("chroot /target /usr/bin/debconf-communicate")

def set_debconf_debian(file):
    f = open(file)

    for line in f.readlines():
        fields = string.split(line, None, 2)
        if len(fields) == 2:
            if fields[0] != fields[1]:
                debconf_comm_process.tochild.write("unregister %s\n"
                                                   % fields[1])
                garbage = debconf_comm_process.fromchild.readline()
        elif len(fields) == 3:
            if fields[0] != fields[1]:
                debconf_comm_process.tochild.write("register %s %s\n"
                                                   % (fields[0], fields[1]))
                garbage = debconf_comm_process.fromchild.readline()
            debconf_comm_process.tochild.write("set %s %s"
                                               % (fields[1], fields[2]))
            garbage = debconf_comm_process.fromchild.readline()
            debconf_comm_process.tochild.write("fset %s isdefault false"
                                               % fields[1])
            garbage = debconf_comm_process.fromchild.readline()

    f.close()

def shutdown_debconf_debian():
    debconf_comm_process.tochild.close()
    debconf_comm_process.wait()

# For now, let's use the Progeny system and supply a "setdebconf" for
# Debian.

init_debconf = init_debconf_progeny
set_debconf = set_debconf_progeny
shutdown_debconf = shutdown_debconf_progeny

#  if os.path.exists("/bin/setdebconf"):
#      init_debconf = init_debconf_progeny
#      set_debconf = set_debconf_progeny
#      shutdown_debconf = shutdown_debconf_progeny
#  else:
#      init_debconf = init_debconf_debian
#      set_debconf = set_debconf_debian
#      shutdown_debconf = shutdown_debconf_debian

# First things first: we need to wrap the whole thing in an exception
# loop, and trap any exceptions that happen so we can print them
# cleanly.

try:

    # Initialize some global settings.

    sys.exitfunc = exitfunc
    debug = 0
    config_fstype_allowed = ["ext2", "msdos"]

    scsiloaded = 0
    netloaded = 0
    xserver_found = 0
    cmdlinecfg = {}
    globalcfg = {}
    scsimods = ["ide-scsi"]
    netmods = []
    cfgpath = "/etc"

    required_pkgs = ["grub", "apt-utils", "debconf", "debconf-utils", \
                     "makedev", "hostname"]

    # If we're doing X configuration, make sure we include a few more
    # required packages.

    if not globalcfg.has_key("noxconf"):
        for x_required_pkg in ("mdetect", "read-edid", "discover"):
            required_pkgs.append(x_required_pkg)

    # Get the necessary things mounted and created that aren't on the
    # ramdisk image.

    print """
Debian Installation Floppy

Initializing system.
"""

    os.mkdir("/proc")
    os.mkdir("/target")
    os.mkdir("/cdrom")
    os.symlink("/cdrom", "/target/cdrom")

    runcmd("mount -t proc proc /proc")

    # Clear out the root device information in the kernel so it
    # doesn't interfere with parted.

    setrootdev = open("/proc/sys/kernel/real-root-dev", "w")
    setrootdev.write("0x0000\n")
    setrootdev.close()

    # Load the kernel command line parameters first, in case we want
    # to load our configuration files from somewhere strange.

    proccmdfile = open("/proc/cmdline")
    proccmd = proccmdfile.readlines()
    proccmdfile.close()
    for procline in proccmd:
        cmditems = string.split(procline)
        for cmditem in cmditems:
            if string.find(cmditem, "=") != -1:
                (name, value) = string.split(cmditem, "=", 2)
                cmdlinecfg[name] = value
            else:
                cmdlinecfg[cmditem] = ""

    # Are there any modules to load as an immediate first step?  This
    # may be needed if we need to load the configuration off of the
    # SCSI hard disk.

    if os.path.exists("/etc/scsip1.lst"):
        scsimodfile = open("/etc/scsip1.lst", "r")
        scsimods.extend(load_config_lines(scsimodfile))
        scsimodfile.close()

        if cmdlinecfg.has_key("aidrv"):
            print """
Looking for SCSI devices that might be necessary for loading
configuration information.  If the system seems to hang here, please
reboot and try again.
"""

            detect_hardware()

    # Determine where the config files should be pulled from, and
    # mount the boot floppy (if necessary).

    if not os.path.exists("/etc/global.cfg"):
        sys.stdout.write("Loading configuration from boot floppy...")
        sys.stdout.flush()
        os.mkdir("/bootfloppy")

        autoinst_config_drive = "/dev/fd0u1722"
        autoinst_config_fstype = "msdos"
        if cmdlinecfg.has_key("aidrv"):
            alt_drive = cmdlinecfg["aidrv"]
            if os.path.exists(alt_drive) and \
               stat.S_ISBLK(os.stat(alt_drive)[stat.ST_MODE]):
                autoinst_config_drive = alt_drive
            else:
                print "\nConfig drive %s not found - reverting to floppy." \
                      % alt_drive
        if cmdlinecfg.has_key("aifs"):
            if cmdlinecfg["aifs"] in config_fstype_allowed:
                autoinst_config_fstype = cmdlinecfg["aifs"]
            else:
                print "\nConfig fs type %s not allowed - reverting to 'msdos'" \
                      % cmdlinecfg["aifs"]

        for numtry in range(1, 4):
            try:
                if numtry < 4:
                    runcmd("mount -t %s -o ro %s /bootfloppy"
                           % (autoinst_config_fstype, autoinst_config_drive))
            except RuntimeError:
                print """
Could not mount the install floppy.  Please reinsert the install floppy
and press Enter to continue.
"""
                sys.stdin.readline()
            else:
                break
        if numtry == 4:
            raise RuntimeError, "could not load configuration"

        if os.path.exists("/bootfloppy/conf.tgz"):
            runcmd("/bin/sh -c 'cd /etc; zcat /bootfloppy/conf.tgz | tar -x -f -'")
        elif os.path.isdir("/bootfloppy/conf"):
            runcmd("cp /bootfloppy/conf/* /etc")
        else:
            print "\nERROR: Configuration files not found!  Cannot continue."
            killsystem()

        runcmd("umount /bootfloppy")
        print "done."
        print "It is safe to remove the boot floppy."
        time.sleep(5)
    else:
        print "Using configuration found in /etc."

    # At this stage, we need to load global configuration and module lists
    # first.  The rest of the configuration information should only be
    # loaded if we really need it.

    # Globals.

    print "\nLoading global configuration..."

    globalfile = open("%s/global.cfg" % cfgpath, "r")
    globalcfg = load_config_pairs(globalfile)
    globalfile.close()

    # Special config option - detect if we're trying to install a
    # Progeny system.  If so, set the special global flag "progeny".

#      if os.path.exists("/bin/setdebconf"):
#          globalcfg["progeny"] = ""

    # Proxy support for all HTTP-using tools is set with a single
    # environment variable, so let's just set it now so all the tools
    # recognize it.

    if globalcfg.has_key("proxy"):
        os.environ["http_proxy"] = globalcfg["proxy"]

    # Now set debug flag.

    if globalcfg.has_key("debug"):
        debug = 1

    # SCSI module list.

    print "Loading module lists..."

    if os.path.exists("%s/scsimod.lst" % cfgpath):
        scsimodfile = open("%s/scsimod.lst" % cfgpath, "r")
        scsimods.extend(load_config_lines(scsimodfile))
        scsimodfile.close()

    # Network module list.

    if os.path.exists("%s/netmod.lst" % cfgpath):
        netmodfile = open("%s/netmod.lst" % cfgpath, "r")
        netmods.extend(load_config_lines(netmodfile))
        netmodfile.close()

    # Discover hardware and load any necessary devices.

    print """
Now detecting hardware.  Only SCSI adapters and network adapters are
discovered here.  More modules should load at this point, although
they may not need to if you do not have either SCSI or network
adapters on your system.

If the system seems to hang, please reboot and try again.

"""

    detect_hardware()

    # Load network database.

    if globalcfg["network"] == "netdb":
        print "Reading network database..."

        netdb = []
        netsettings = {}
        defaultsettings = None
        issettings = 1
        netfile = open("%s/network.cfg" % cfgpath, "r")

        for cfgitem in load_config_items(netfile):
            if len(cfgitem) < 1:
                if issettings:
                    issettings = 0
                else:
                    issettings = 1
                    netsettings = {}
                continue

            if issettings:
                netsettings[cfgitem[0]] = cfgitem[1]
            else:
                newsettings = copy.copy(netsettings)
                newsettings["macaddr"] = string.upper(cfgitem[0])
                newsettings["ip"] = cfgitem[1]
                if len(cfgitem) > 2:
                    newsettings["hostname"] = cfgitem[2]
                if newsettings["macaddr"] == "DEFAULT":
                    defaultsettings = newsettings
                else:
                    netdb.append(newsettings)

        netfile.close()

    # Configure the network.

    if netloaded and globalcfg["network"] != "none":
        print "Configuring the network..."

        runcmd("ifconfig lo 127.0.0.1")

        if globalcfg["network"] == "netdb":
            hwaddr = ""
            ifline = runpipe("ifconfig eth0")[0]
            if ifline[-1] == "\n":
                ifline = ifline[:-1]
            hwindex = string.find(ifline, "HWaddr")
            if hwindex < 0:
                print "Skipping network configuration."
            else:
                hwaddr = string.strip(ifline[hwindex + 7:])
                hwaddr = string.replace(hwaddr, ":", "")

                macfound = 0
                for netsettings in netdb:
                    if netsettings["macaddr"] == hwaddr:
                        print "Found network configuration in database."
                        mysettings = netsettings
                        macfound = 1
                        break
                if not macfound and defaultsettings:
                    print "Using default settings in database."
                    mysettings = defaultsettings
                    macfound = 1

                if macfound:
                    runcmd("ifconfig eth0 %s netmask %s broadcast %s" %
                           (mysettings["ip"], mysettings["netmask"],
                            mysettings["broadcast"]))
                    if mysettings.has_key("gateway"):
                        runcmd("route add default gw %s" %
                               mysettings["gateway"])
                    resolv = open("/etc/resolv.conf", "w")
                    resolv.write("nameserver %s\n" %
                                 mysettings["nameserver"])
                    resolv.close()

        elif globalcfg["network"] == "dhcp":
            os.mkdir("/var")
            os.mkdir("/var/run")
            try:
                runcmd("pump -i eth0")
            except RuntimeError:
                print "Error configuring the network via DHCP."
                netloaded = 0
            else:
                print "Network configured via DHCP."
        else:
            raise RuntimeError, "unsupported network configuration type"

    # If a certain configuration option is specified (either in the
    # global configuration or via the command line), attempt to mount
    # the CD via NFS.

    cddevpath = ""
    if (globalcfg.has_key("nfscd") or cmdlinecfg.has_key("nfscd")) \
       and netloaded:
        print "Attempting to mount the CD via NFS..."

        if cmdlinecfg.has_key("nfscd"):
            nfspath = cmdlinecfg["nfscd"]
        else:
            nfspath = globalcfg["nfscd"]
        cdmountoutput = runpipe("mount %s /cdrom" % nfspath)
        cddevpath = nfspath
        cddevoptions = ""

    # Otherwise, mount the CD, if it's available.

    else:
        print """
Looking for CDs to mount.  You may see errors here if you don't have
any CDs in your CD drives.

"""

        cddiscover = runpipe("discover --device cdrom")
        for cddrv in cddiscover:
            if cddrv[-1] == "\n":
                cddrv = cddrv[:-1]

            try:
                cdmountoutput = runpipe("mount -t iso9660 -o ro,exec %s /cdrom"
                                        % cddrv)
                cddevpath = cddrv
                cddevoptions = "-t iso9660 -o ro,exec"
            except RuntimeError:
                continue
            else:
                break

    # If we're configured to do an interactive install, exec the
    # interactive install script.  The interactive installer is
    # expected to set the dpkg selections and write any needed debconf
    # settings to /etc/capplet.cfg.  Additionally, the interactive
    # installer should either partition and mount the drives itself,
    # or it should write its own /etc/partinfo.cfg so this script can
    # do the dirty work.

    mountlist = []
    freelist = []

    if globalcfg.has_key("interactive"):
        print "Starting interactive installation..."

        if os.path.exists("/bin/installer"):
            installer = "/bin/installer"
        else:
            installer = "/cdrom/live/sbin/installer"
        if os.path.exists("/bin/installer.glade"):
            instglade = "/bin/installer.glade"
        else:
            instglade = "/cdrom/live/sbin/installer.glade"

        os.unlink("%s/partinfo.cfg" % cfgpath)
        os.unlink("%s/select.cfg" % cfgpath)

        os.unlink("/usr")
        os.symlink("/cdrom/live", "/usr")
        os.mkdir("/tmp")

    ##    os.rename("/etc/ldsoint.cnf", "/etc/ld.so.conf")

        os.environ["PATH"] = "/cdrom/live/bin:/bin"
        os.environ["LD_LIBRARY_PATH"] = "/cdrom/live/lib:/lib"

        runcmd("mknod /dev/psaux c 10 1")

    ##    runcmd("/bin/sh -c 'X -xf86config /cdrom/live/etc/XF86Config &'")
    ##    os.environ["DISPLAY"] = ":0"
    ##    runcmd("/bin/sh -c '%s %s'" % (installer, instglade))

        runcmd("xinit %s %s -- -xf86config /cdrom/live/etc/XF86Config" \
               % (installer, instglade))

        os.environ["PATH"] = "/bin"
        os.environ["LD_LIBRARY_PATH"] = "/lib"

        # Allow the installer to override any global configuration
        # items it needs.

        if os.path.exists("%s/interactive.cfg" % cfgpath):
            intfile = open("%s/interactive.cfg" % cfgpath)
            intline = intfile.readline()
            while intline:
                if intline[-1] == "\n":
                    intline = intline[:-1]

                cfgitems = string.split(intline)
                if len(cfgitems) == 1:
                    globalcfg[cfgline] = ""
                else:
                    globalcfg[cfgitems[0]] = cfgitems[1]
                intline = intfile.readline()
            intfile.close()

        # If the partinfo file doesn't exists, the interactive script
        # is assumed to have done all the partitioning, formatting,
        # mounting, etc.  In this case, we need to look at the
        # system's current mount structure to fill the mountlist
        # structure.

        if not os.path.exists("%s/partinfo.cfg" % cfgpath):
            mtab = open("/etc/mtab")
            mtabline = mtab.readline()
            while mtabline:
                mtabfields = string.split(mtabline)
                if mtabfields[1][:7] == "/target" and \
                   mtabfields[1] != "/target/cdrom":
                    realpath = mtabfields[1][8:]
                    if realpath == "/":
                        bootdrv = mtabfields[0]
                    mountlist.append((0, mtabfields[0], realpath, mtabfields[2]))
                mtabline = mtab.readline()
            mtab.close()

    # Unmount the CD if it's mounted.

    if cddevpath:
        runcmd("/bin/umount /cdrom")

    # Now we need to check to see if the interactive installer did any
    # partitioning, or if we have to do it.  If we don't have to do
    # any partitioning, we skip past a lot of stuff.

    if os.path.exists("%s/partinfo.cfg" % cfgpath):

    # Load partition information from the floppy, if necessary.

        print "Reading partition configuration..."

        partfile = open("%s/partinfo.cfg" % cfgpath, "r")
        partcfg = load_config_items(partfile)
        partfile.close()

        for partitem in partcfg:
            if len(partitem) == 4:
                parthints = string.split(partitem[-1], ",")
                partitem[-1] = parthints
            elif len(partitem) == 3:
                partitem.append([])
            else:
                raise RuntimeError, "invalid format for partinfo.cfg"

    # Find all drives.

        print "Searching for drives..."

        drvlist = []
        parted.init()
        parted.device_probe_all()

    # For now, pick the first drive to work with; we can't do multiple
    # disks yet.

        drvinstlist = [parted.get_devices()[0]]

    # Check drives for existing partition tables; if there are any,
    # either print a big nasty warning or stop, depending on
    # configuration.

        print "Examining drives..."

        bootdrv = ""
        for drv in drvinstlist:
            if not bootdrv:
                bootdrv = drv.get_path()

            drvdisk = drv.disk_open()
            if drvdisk is not None:
                partlist = drvdisk.get_part_list()
                isdata = 0
                for part in partlist:
                    if part.get_type() != parted.PED_PARTITION_FREESPACE:
                        isdata = 1

                drvdisk.close()

                if isdata and not globalcfg.has_key("freespace"):
                    if not globalcfg.has_key("nosafe"):
                        print "Error: drive %s already partitioned!" % \
                              drv.get_path()
                        print """
The drive selected for automatic partitioning has already been
partitioned.  This installation profile is configured to be safe, so
no partitioning has been done.  If you really want to reinstall this
system, please remove all partitions from the disk manually, or use a
different installation profile that is not configured to be safe.
"""
                        killsystem()
                    elif not globalcfg.has_key("nosafewarn"):
                        print "\n\n=======> WARNING!!! <======\n\n"
                        print "Drive %s already partitioned!" % drv.get_path()
                        print """
The drive selected for automatic partitioning has already been
partitioned.  This installation profile is configured to be unsafe.
Thus, partitioning will commence in 10 seconds.  To prevent this, you
may reset the machine or turn off the power.  This will not affect any
currently mounted filesystems, and will preserve all partitioning
currently on the drive.

"""
                        time.sleep(10)
                        print "Proceeding!"
                        time.sleep(2)

    # Partition and format drive.

        for drv in drvinstlist:
            print "Partitioning drive %s..." % drv.get_path()

            drvobj = partition.Partition(drv)

            drvsectors = drv.get_length()

            if not globalcfg.has_key("freespace"):
                drvobj.create_partition_table()

            # FIXME: It would be nice to have a more sophisticated
            # free space handling system.

            freelist = drvobj.get_freespace()
            curpartend = freelist[0][0]

            partabssect = 0
            for partinfo in partcfg:
                if partinfo[2] == "/":
                    rootpart = partinfo
                partsizetype = string.upper(partinfo[1][-1])
                if partsizetype == "M":
                    partsize = string.atoi(partinfo[1][:-1])
                    partsect = int(float(partsize) * 1024 * 1024 / parted.SECTOR_SIZE)
                    partabssect = partabssect + partsect
                elif partsizetype != "%":
                    raise RuntimeError, "invalid partition size specifier"
            partremsect = drvsectors - partabssect - curpartend

            partcfg.remove(rootpart)
            partcfg.insert(0, rootpart)

            for (partfs, partsizestr, partmount, parthints) in partcfg:
                print "Creating %s partition for %s..." % (partfs, partmount)
                partsizetype = string.upper(partsizestr[-1])
                partsize = string.atoi(partsizestr[:-1])

                if partfs == "swap":
                    partfs = "linux-swap"
                partfstype = parted.file_system_type_get(partfs)

                if partsizetype == "%":
                    partsect = int(partremsect * (float(partsize) / 100))
                else:
                    partsect = int(float(partsize) * 1024 * 1024 / parted.SECTOR_SIZE)

                partdevice = drvobj.create_partition(curpartend,
                                                     curpartend + partsect - 1,
                                                     partfstype, parthints)
                mountlist.append([partdevice, partmount, partfs])
                curpartend = curpartend + partsect

            drvobj.commit_changes()

            drvdisk = drv.disk_open()
            for (partdevice, partmount, partfs) in mountlist:
                print "Creating %s file system on %s..." % (partfs, partdevice)

                drvpartnumstr = partdevice[-2:]
                if drvpartnumstr[0] not in string.digits:
                    drvpartnumstr = drvpartnumstr[1]
                drvpartnum = string.atoi(drvpartnumstr)

                partfstype = parted.file_system_type_get(partfs)
                drvnewpart = drvdisk.get_partition(drvpartnum)
                parted.FileSystem(drvnewpart.get_geom(), partfstype).close()

            drvdisk.close()
            drv.close()

    # Since we're done with partitioning, we can call this now.  This
    # ensures that the partition table is reread by the system.  It's
    # important not to call parted for anything after this.

        parted.done()

    # Mount drives.

        print "Mounting drives..."

        for (partdevice, partmount, partfs) in mountlist:
            if partfs == "linux-swap":
                runcmd("swapon %s" % partdevice)
            else:
                partmntpath = "/target"
                partmntparts = string.split(partmount, "/")
                for partmntpart in partmntparts:
                    if partmntpart == "":
                        continue
                    partmntpath = partmntpath + "/" + partmntpart
                    if not os.path.isdir(partmntpath):
                        os.mkdir(partmntpath)
                runcmd("mount -t %s %s /target%s"
                       % (partfs, partdevice, partmount))

    # Done with partitioning and formatting stuff; if the interactive
    # installer took care of that for us, this is where the install
    # should pick up.

    # Remount the CD in the right place.

    if not os.path.exists("/target/cdrom"):
        os.mkdir("/target/cdrom")
    if cddevpath:
        runcmd("/bin/mount %s %s /target/cdrom" % (cddevpath, cddevoptions))
        os.rmdir("/cdrom")
        os.symlink("/target/cdrom", "/cdrom")

    os.environ["PATH"] = "/bin:/sbin:/usr/bin:/usr/sbin"
    os.environ["LD_LIBRARY_PATH"] = "/lib:/usr/lib"

    # Locate base system archive; pull it down off the network if
    # necessary.  This is skipped if the interactive install installed
    # the base system for us.

    if not os.path.exists("/target/usr/bin"):
        print "Locating base system."

        try:
            if globalcfg["baseurl"][:5] == "http:":
                print "Downloading base system from the network..."
                runcmd("wget -O /target/base.tgz %s" % globalcfg["baseurl"])
                basepath = "/target/base.tgz"
            elif globalcfg["baseurl"][:6] == "cdrom:":
                basepath = "/target/cdrom/" + globalcfg["baseurl"][6:]
                if not os.path.exists(basepath):
                    raise RuntimeError, "cannot locate CD base system"
            else:
                raise RuntimeError, "cannot locate base system in config"
        except RuntimeError:
            print """
The system was unable to locate the base system.  Please check for
errors in the above messages, and reboot to try again.

"""
            killsystem()

    # Untar the base system from the archive.

        print "Extracting base system..."

        runcmd("sh -c 'cd /target; zcat %s | tar -x -f -'" % basepath)

        if basepath[:7] == "/cdrom":
            os.unlink(basepath)

    # Mount a second /proc for chrooted utilities.

    runcmd("mount -t proc proc /target/proc")
    mountlist.append(["proc", "/proc", "proc"])

    # Write /etc/fstab.

    fstab = open("/target/etc/fstab", "a")

    fstab.write("""# /etc/fstab: static file system information.
#
# <file system> <mount point> <type> <options> <dump> <pass>
""")
    for (partdevice, partmount, partfs) in mountlist:
        if partfs == "linux-swap":
            fstab.write("%s\tnone\tswap\tsw\t0\t0\n" % partdevice)
        else:
            if partmount == "/":
                mntoptions = "defaults,errors=remount-ro"
                rootdev = partdevice
                dumppriority = 1
            elif partfs == "proc":
                mntoptions = "defaults"
                dumppriority = 0
            else:
                mntoptions = "defaults"
                dumppriority = 2
            fstab.write("%s\t%s\t%s\t%s\t0\t%d\n" % (partdevice, partmount,
                                                     partfs, mntoptions,
                                                     dumppriority))

    fstab.write("""/dev/fd0\t/floppy\tauto\tdefaults,user,noauto\t0\t0
/dev/cdrom\t/cdrom\tiso9660\tdefaults,ro,user,noauto\t0\t0
""")

    fstab.close()

    # Set the root password.

    if os.path.exists("/target/etc/shadow"):
        pwdpath = "/target/etc/shadow"
    else:
        pwdpath = "/target/etc/passwd"

    oldpwd = open(pwdpath, "r")
    newpwd = open(pwdpath + ".new", "w")

    pwdline = oldpwd.readline()
    while pwdline:
        if pwdline[:4] == "root":
            pwdend = string.index(pwdline[5:], ":") + 5
            newpwdline = pwdline[:5] + globalcfg["rootpwd"] + pwdline[pwdend:]
        else:
            newpwdline = pwdline
        newpwd.write(newpwdline)
        pwdline = oldpwd.readline()

    oldpwd.close()
    newpwd.close()

    os.remove(pwdpath)
    os.rename(pwdpath + ".new", pwdpath)

    # Copy sources.list to the archive and update dpkg and apt.

    print "Configuring package system..."

    for copy_file in ("/etc/resolv.conf", "/etc/hosts"):
        if os.path.exists(copy_file):
            runcmd("cp %s /target/etc" % copy_file)

    if globalcfg.has_key("cdinst"):
        sourceslist = open("/target/etc/apt/sources.list", "w")
        sourceslist.close()

        runcmd("chroot /target apt-cdrom -d /cdrom -m add")
    else:
        runcmd("cp %s/sources.lst /target/etc/apt/sources.list" % cfgpath)

    runcmd("chroot /target apt-get update")
    runcmd("chroot /target /bin/sh -c 'apt-cache dumpavail > /tmp/apt-avail'")
    runcmd("chroot /target /bin/sh -c 'dpkg --update-avail /tmp/apt-avail'")
    os.unlink("/target/tmp/apt-avail")

    # Set the package selections.

    kernel_img_pkgs = []
    if os.path.exists("%s/select.cfg" % cfgpath):
        print "Setting package selections..."
        dpkgpipe = os.popen("chroot /target /usr/bin/dpkg --set-selections", "w")
        selectionsfile = open("%s/select.cfg" % cfgpath)

        selectionsline = selectionsfile.readline()
        while selectionsline:
            if selectionsline[:7] == "xserver":
                xserver_found = 1

            if selectionsline[:12] == "kernel-image":
                selectionsinfo = string.split(selectionsline, None, 1)
                kernel_img_pkgs.append(selectionsinfo[0])

            dpkgpipe.write(selectionsline)
            selectionsline = selectionsfile.readline()

        for pkg in required_pkgs:
            dpkgpipe.write("%s install\n" % pkg)

        selectionsfile.close()
        dpkgpipe.close()

        apt_list_command = "apt-get --print-uris dselect-upgrade"
        apt_download_command = "apt-get -dyf dselect-upgrade"
        apt_install_command = "apt-get -yf dselect-upgrade"

    elif os.path.exists("%s/pkgsel.cfg" % cfgpath):
        print "Preparing package sets for installation..."
        selectioncmdline = ""
        selectionsfile = open("%s/pkgsel.cfg" % cfgpath)
        for selectionsline in selectionsfile.readlines():
            if selectionsline[-1] == "\n":
                selectionsline = selectionsline[:-1]
            selectioncmdline = selectioncmdline + " " + selectionsline
        selectionsfile.close()

        apt_list_command = ""
        apt_download_command = "apt-pkgset -d install %s" % selectioncmdline
        apt_install_command = "apt-pkgset install %s" % selectioncmdline
    else:
        apt_list_command = "apt-get --print-uris dselect-upgrade"
        apt_download_command = "apt-get -dyf dselect-upgrade"
        apt_install_command = "apt-get -yf dselect-upgrade"

    # Pre-download packages to allow debconf seeding.

    pkgsuccess = 0
    print "Downloading packages..."
    for numtry in range(1, 3):
        try:
            print "Downloading packages - try %d..." % numtry
            runcmd("chroot /target /bin/sh -c '%s'" % apt_download_command)
        except RuntimeError:
            if numtry < 3:
                print "Apt reported a problem downloading; will try again."
                time.sleep(5)
        else:
            pkgsuccess = 1
            break

    if not pkgsuccess:
        raise RuntimeError, "unable to download packages"

    # Update dpkg and apt to the latest versions.

    #runcmd("chroot /target /bin/sh -c 'apt-get -yf install dpkg apt'")

    # Make sure required packages are installed.

    runcmd("chroot /target /bin/sh -c 'apt-get -yf install %s'"
           % string.join(required_pkgs, " "))

    # Check to see if device files have been created; if not,
    # create them.

    if not os.path.exists("/target/dev/hda1"):
        device_all = ["generic", "hde", "hdf", "hdg", "hdh", "sde", "sdf",
                      "sdg", "sdh", "scd-all", "initrd", "rtc", "input",
                      "ida"]
        device_i386 = ["isdn-io", "eda", "edb", "sonycd", "mcd",
                       "mcdx", "cdu535", "lmscd", "sbpcd", "aztcd", "bpcd",
                       "optcd", "sjcd", "cm206cd", "gscd", "dac960", "ida"]
        for device in device_all + device_i386:
            try:
                runcmd("chroot /target /bin/sh -c 'cd /dev; MAKEDEV %s'"
                       % device)
            except RuntimeError:
                pass

    # Load templates from packages.

    print "Loading configuration data..."

    if globalcfg.has_key("progeny"):
        runcmd("cp /bin/preppkgs /target/tmp")
        runcmd("chroot /target /tmp/preppkgs /var/cache/apt/archives")

#      preppkgs = os.popen("chroot /target /tmp/preppkgs", "w")

#      for pkgfile in os.listdir("/target/var/cache/apt/archives"):
#          if pkgfile[-3:] != "deb":
#              continue
#          preppkgs.write("/var/cache/apt/archives/%s\n" % pkgfile)

#      if preppkgs.close() is not None:
#          raise RuntimeError, "error loading package configuration info"

        os.unlink("/target/tmp/preppkgs")
    else:
        for template_info in runpipe("chroot /target /bin/sh -c 'apt-extracttemplates /var/cache/apt/archives/*deb'"):
            if template_info[:5] == "Check":
                continue

            (package, version, template, config) = string.split(template_info,
                                                                " ")
            runcmd("chroot /target /usr/bin/debconf-loadtemplate %s %s"
                   % (package, template))

    # Apply customized debconf values to the debconf database, if
    # necessary.

    init_debconf()

    if os.path.exists("%s/debconf.cfg" % cfgpath):
        set_debconf("%s/debconf.cfg" % cfgpath)

    # Apply interactive information to the debconf database, if
    # necessary.

    if os.path.exists("%s/interactive.cfg" % cfgpath):
        set_debconf("%s/interactive.cfg" % cfgpath)

    # Apply network configuration.  If the system is running Progeny
    # Debian, use etherconf to set the network up.  Otherwise, just
    # write /etc/network/interfaces directly.

    print "Applying network configuration to the base system..."

    if globalcfg.has_key("progeny"):
        etherconfcfg = open("/target/tmp/etherconf.cfg", "w")
        etherconfcfg.write("""etherconf/configure etherconf/configure true
etherconf/removable etherconf/removable false
etherconf/replace-existing-files etherconf/replace-existing-files true
""")
        if globalcfg["network"] == "netdb":
            if mysettings.has_key("hostname"):
                nethostname = mysettings["hostname"]
            else:
                nethostname = "autoinst"
            etherconfcfg.write("""etherconf/dhcp-p etherconf/dhcp-p false
etherconf/ipaddr etherconf/ipaddr %s
etherconf/netmask etherconf/netmask %s
etherconf/gateway etherconf/gateway %s
etherconf/hostname etherconf/hostname %s
etherconf/domainname etherconf/domainname %s
etherconf/nameservers etherconf/nameservers %s
""" % (mysettings["ip"], mysettings["netmask"], mysettings["gateway"],
       nethostname, mysettings["domain"], mysettings["nameserver"]))
        elif globalcfg["network"] == "dhcp" or globalcfg["network"] == "none":
            etherconfcfg.write("""etherconf/dhcp-p true
etherconf/dhcphost etherconf/dhcphost \"\"
etherconf/hostname etherconf/hostname autoinst
""")
        else:
            raise RuntimeError, "invalid network configuration"

        etherconfcfg.close()

        set_debconf("/target/tmp/etherconf.cfg")
        runcmd("chroot /target /var/lib/dpkg/info/etherconf.postinst configure")
        os.unlink("/target/tmp/etherconf.cfg")
    else:
        if not os.path.isdir("/target/etc/network"):
            os.mkdir("/target/etc/network")
        ifaces = open("/target/etc/network/interfaces", "w")
        ifaces.write("# /etc/network/interfaces -- see ifup(8)\n\n")
        if globalcfg["network"] != "none":
            ifaces.write("auto lo\n\n")
        else:
            ifaces.write("auto lo eth0\n\n")

        ifaces.write("""# Loopback
iface lo inet loopback
""")
        if globalcfg["network"] != "none":

            # Straight Debian - no etherconf.

            ifaces.write("""
# First network card - created by the autoinstaller.
auto eth0
""")

            if globalcfg["network"] == "netdb":
                ifaces.write("""iface eth0 inet static
\taddress %s
\tnetmask %s
\tgateway %s
""" % (mysettings["ip"], mysettings["netmask"], mysettings["gateway"]))

                # We also need to write /etc/resolv.conf, since DHCP
                # won't be feeding us a nameserver and domain.

                resolvconf = open("/target/etc/resolv.conf", "w")
                resolvconf.write("domain %s\nnameserver %s\n" %
                                 (mysettings["domain"],
                                  mysettings["nameserver"]))
                resolvconf.close()

                # Settings for /etc/hostname and /etc/hosts.
                if mysettings.has_key("hostname"):
                    nethostname = mysettings["hostname"]
                else:
                    nethostname = "autoinst"

                nethostip = mysettings["ip"]

            elif globalcfg["network"] == "dhcp":
                ifaces.write("iface eth0 inet dhcp\n")

                nethostname = "autoinst"
                nethostip = "127.0.0.1"
            else:
                raise RuntimeError, \
                      "unknown network type '%s'" % globalcfg["network"]

            # Still need to write /etc/hostname and /etc/hosts.

            etchostname = open("/target/etc/hostname", "w")
            etchostname.write(nethostname)
            etchostname.close()

            runcmd("chroot /target hostname %s" % nethostname)

            etchosts = open("/target/etc/hosts", "w")
            etchosts.write("127.0.0.1\tlocalhost\n%s\t%s\n" %
                           (nethostip, nethostname))
            etchosts.close()

        ifaces.close()

    # Update discover to prepare for X installation.

    ##runcmd("chroot /target /bin/sh -c 'apt-get -yf install discover'")

    # Detect hardware for X and write the results (if desired).

    if not globalcfg.has_key("noxconf") and xserver_found:
        print "Detecting video hardware.  You may see the screen flash a few times."

        xserverinfo = []
        xdriverinfo = []
        vcardinfo = []
        mouseinfo = []
        edidinfo = []
        xserver = "xserver-xfree86"
        xdriver = "vga"
        cardvendor = "Unknown"
        cardmodel = "VGA Card"
        mouseport = "/dev/psaux"
        mouseprotocol = "PS/2"
        monitorid = "Unknown Monitor"
        horizsync = "28-50"
        vertrefresh = "43-75"

        try:
            xserverinfo = runpipe(
                "chroot /target discover --format=\"%S\\\\n\" video"
                )
        except RuntimeError:
            pass
        try:
            xdriverinfo = runpipe(
                "chroot /target discover --format=\"%D\\\\n\" video"
                )
        except RuntimeError:
            pass
        try:
            vcardinfo = runpipe(
                "chroot /target discover --format=\"%V\\\\n%M\\\\n\" video"
                )
        except RuntimeError:
            pass
        try:
            mouseinfo = runpipe("chroot /target mdetect -x")
        except RuntimeError:
            pass
        try:
            edidinfo = runpipe(
                "chroot /target /bin/sh -c 'get-edid 2>/dev/null | parse-edid 2>/dev/null'"
                )
        except RuntimeError:
            pass

        for infolist in (xserverinfo, xdriverinfo, vcardinfo, mouseinfo, edidinfo):
            for infoindex in range(0, len(infolist)):
                if infolist[infoindex][-1] == "\n":
                    infolist[infoindex] = infolist[infoindex][:-1]

        if len(xserverinfo):
            xserver = xserverinfo[-1]
        if len(xdriverinfo):
            xdriver = xdriverinfo[-1]
        if len(vcardinfo):
            (cardvendor, cardmodel) = vcardinfo[-2:]
        if len(mouseinfo):
            (mouseport, mouseprotocol) = mouseinfo

        if string.find(xserver, "_") != -1:
            xserver_pkg = xserver[string.find(xserver, "_") + 1:]
        else:
            xserver_pkg = xserver
        xserver_pkg = "xserver-%s" % string.lower(xserver_pkg)
        dpkgpipe = os.popen("chroot /target /usr/bin/dpkg --set-selections",
                            "w")
        dpkgpipe.write("%s install" % xserver_pkg)
        dpkgpipe.close()

        try:
            runcmd("chroot /target /bin/sh -c '%s'" % apt_download_command)
        except RuntimeError:
            pass

        for infoline in edidinfo:
            if string.find(infoline, "Identifier") != -1:
                monitorid = infoline[string.index(infoline, '"'):string.rindex(infoline, '"') + 1]
                if monitorid[0] == '"' and monitorid[-1] == '"':
                    monitorid = monitorid[1:-1]
            elif string.find(infoline, "HorizSync") != -1:
                horizsync = string.split(infoline)[1]
            elif string.find(infoline, "VertRefresh") != -1:
                vertrefresh = string.split(infoline)[1]

        xconf = open("/target/tmp/xconf.cfg", "w")

        xconf.write("""
shared/default-x-server shared/default-x-server %s
shared/xfree86v3/clobber_XF86Config shared/xfree86v3/clobber_XF86Config Yes
xserver-xfree86/clobber_XF86Config-4 xserver-xfree86/clobber_XF86Config-4 Yes
xserver-xfree86/config/device/driver xserver-xfree86/config/device/driver %s
xserver-xfree86/config/device/identifier xserver-xfree86/config/device/identifier %s %s
xserver-xfree86/config/inputdevice/mouse/retry_detection xserver-xfree86/config/inputdevice/mouse/retry_detection No
xserver-xfree86/config/inputdevice/mouse/port xserver-xfree86/config/inputdevice/mouse/port %s
xserver-xfree86/config/inputdevice/mouse/protocol xserver-xfree86/config/inputdevice/mouse/protocol %s
xserver-xfree86/config/monitor/selection-method xserver-xfree86/config/monitor/selection-method Simple
xserver-xfree86/config/monitor/screen-size xserver-xfree86/config/monitor/screen-size 15 inches (380 mm)
xserver-xfree86/config/monitor/identifier xserver-xfree86/config/monitor/identifier %s
xserver-xfree86/config/monitor/horiz-sync xserver-xfree86/config/monitor/horiz-sync %s
xserver-xfree86/config/monitor/vert-refresh xserver-xfree86/config/monitor/vert-refresh %s
""" % (xserver_pkg, xdriver, cardvendor, cardmodel, mouseport, mouseprotocol,
       monitorid, horizsync, vertrefresh))

        xconf.close()

        set_debconf("/target/tmp/xconf.cfg")
        os.unlink("/target/tmp/xconf.cfg")

    # Set debconf configuration in the environment.
    os.environ["DEBIAN_FRONTEND"] = "noninteractive"
    os.environ["DEBIAN_PRIORITY"] = "high"

    # Set special kernel configuration to prevent kernel postinst message.

    kernelcfg = open("/target/etc/kernel-img.conf", "w")
    kernelcfg.write("""
do_symlink = Yes
clobber_modules = YES
do_bootfloppy = NO
do_bootloader = NO
relative_links = YES
""")
    kernelcfg.close()

    # We're done playing with debconf now.

    shutdown_debconf()

    # Install all kernel packages.  This is done separately because the
    # kernel packages may display a warning and ask the user to press
    # Enter; we don't need to worry about the warning (since it's about
    # installing the currently running kernel, which we know we're doing).

    for kernel_img_pkg in kernel_img_pkgs:
        runcmd("chroot /target /bin/sh -c 'yes | apt-get -yf install %s'"
               % kernel_img_pkg)

    # Install all additional packages.  If we've done our homework, this
    # should run without interruption.

    print "Installing packages..."

    runcmd("chroot /target /bin/sh -c 'apt-get -yf install'")
    runcmd("chroot /target /bin/sh -c 'apt-get -yf install dpkg'")

    os.rename("/target/sbin/start-stop-daemon", "/target/sbin/start-stop-daemon.disabled")
    runcmd("cp /target/bin/true /target/sbin/start-stop-daemon")

    pkgsuccess = 0
    maxtries = 3
    for numtry in range(1, maxtries):
        try:
            print "Running apt - try %d..." % numtry
            runcmd("chroot /target /bin/sh -c '%s'" % apt_install_command)
        except RuntimeError:
            if numtry < maxtries:
                print "Apt reported a problem; will try again."
                time.sleep(5)
        else:
            pkgsuccess = 1
            break

    if not pkgsuccess:
        raise RuntimeError, "unable to complete installation of packages"

    print "\nDone with packages."

    os.unlink("/target/sbin/start-stop-daemon")
    os.rename("/target/sbin/start-stop-daemon.disabled", "/target/sbin/start-stop-daemon")

    # Remove special kernel configuration file and write a new one
    # (if needed).

    os.unlink("/target/etc/kernel-img.conf")
    if not globalcfg.has_key("progeny"):
        kernel_img = open("/target/etc/kernel-img.conf", "w")
        kernel_img.write("""# GRUB boot options
postinst_hook = /sbin/update-grub
postrm_hook = /sbin/update-grub
do_bootloader = NO
""")
        kernel_img.close()

    # Check the kernel symlinks in /.  If they don't exist, create them.

    kernelpaths = []
    if not os.path.islink("/target/vmlinuz"):
        for bootfile in os.listdir("/target/boot"):
            if bootfile[:7] == "vmlinuz":
                kernelpaths.append("boot/%s" % bootfile)

        if len(kernelpaths):
            kernelpaths.sort()
            kernelpaths.reverse()
            os.symlink(kernelpaths[0], "/target/vmlinuz")
            if len(kernelpaths) > 1:
                os.symlink(kernelpaths[1], "/target/vmlinuz.old")
        else:
            print "No kernel package installed; the system cannot continue."
            killsystem()

    # Install boot loader (whichever one is appropriate).

    print "Installing boot loader..."
    stanzas = [ { "rootdev": rootdev,
                  "kernel": "/vmlinuz" } ]
    boot.setup_boot_loader(stanzas)

    # If X was installed, be sure to re-run dexconf, just to make sure
    # that a configuration file is created.

    if not globalcfg.has_key("noxconf") and xserver_found:
        if os.path.exists("/target/usr/bin/dexconf"):
            try:
                runcmd("chroot /target /usr/bin/dexconf")
            except RuntimeError:
                pass

    # Execute any post-installation scripts specified by the user.

    if os.path.exists("/etc/postinst"):
        print "Running post-installation script..."

        runcmd("cp /etc/postinst /target/tmp")
        os.chmod("/target/tmp/postinst", 0755)

        try:
            runcmd("chroot /target /tmp/postinst")
            os.unlink("/target/tmp/postinst")
        except RuntimeError:
            print """

The postinst script did not run properly.  A copy of the script is
saved in /tmp/postinst if you wish to try manually after
installation.

"""

    # Set the root partition to use when we exit.

    for mountinfo in mountlist:
        if mountinfo[1] == "/":
            rootdevice = mountinfo[0]
            break

    lslines = runpipe("chroot /target /bin/ls -l %s" % rootdevice)
    lsline = lslines[-1]

    lsinfo = string.split(lsline)
    (rootmajor, rootminor) = lsinfo[4:6]
    if rootmajor[-1] == ",":
        rootmajor = rootmajor[:-1]

    rootdevstr = "0x%x%02x" % (int(rootmajor), int(rootminor))

    setrootdev = open("/proc/sys/kernel/real-root-dev", "w")
    setrootdev.write(rootdevstr)
    setrootdev.close()

    # Make sure the base tarball is gone.

    if os.path.exists("/target/base.tgz"):
        os.unlink("/target/base.tgz")

    # Touch /fastboot to ensure that the file system check isn't done
    # afterwards.

    fastboot = open("/target/fastboot", "w")
    fastboot.close()

    # Kill pump off if we're using DHCP.

    if globalcfg["network"] == "dhcp":
        try:
            runcmd("pump -k")
        except RuntimeError:
            print "Unable to shut down the network cleanly!"

    # Kill any processes that might have been started during
    # installation.

    print "Killing unwanted processes..."
    numtries = 0
    foundprocess = 1
    while foundprocess and numtries < 3:
        foundprocess = 0
        numtries = numtries + 1
        for sig in (signal.SIGTERM, signal.SIGKILL):
            for procpath in os.listdir("/proc"):
                fullprocpath = "/proc/%s" % procpath
                if not os.path.isdir(fullprocpath):
                    continue
                if procpath[0] not in string.digits:
                    continue

                procpid = int(procpath)
                if procpid > 100:
                    foundprocess = 1
                    os.kill(procpid, sig)

            sleeptime = time.time()
            while (time.time() - sleeptime) < 2:
                time.sleep(1)

    # Unmount all mounted partitions.

    unmountall()

# End of top-level exception block.  This is where we need to go to
# catch any unexpected errors.

except DebugException, e:
    raise e
except StandardError:
    default_exception_handler()

# Now exit.  This will trigger the kernel to mount our newly created
# root partition and continue the boot process.

sys.exit(0)

# FIXME: Test apparatus!
# This code is here to abort the script at various places, so we can
# check to make sure that things are happening as they should at
# various points.  It should move around during testing, and be
# eliminated entirely in the shipping product.  Because of the -i
# option passed to python above, running this will cause the
# interpreter to take over.

raise DebugException("Debug exception - executed to stopping point.")

# FIXME: Test apparatus!
# This code allows the script to pause and wait for input before
# continuing.  When the script appears to hang at some point, this
# will help us to identify the location better.

sys.stdout.write("Pausing - press Enter to continue... ")
junk = sys.stdin.readline()

# vim:ai:et:sts=4:tw=80:sw=4: