summaryrefslogtreecommitdiffstats
path: root/booty/bootloaderInfo.py
blob: 9f1952ede1a90a5119cb8f42325618b49b8018ae (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
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
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
#
# bootloaderInfo.py - bootloader config object used in creation of new
#                     bootloader configs.  Originally from anaconda
#
# Jeremy Katz <katzj@redhat.com>
# Erik Troan <ewt@redhat.com>
# Peter Jones <pjones@redhat.com>
#
# Copyright 2005-2008 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import os, sys
import crypt
import random
import shutil
import string
import struct
from copy import copy

from lilo import LiloConfigFile
import rhpl
from rhpl.translate import _, N_
import rhpl.executil

from flags import flags
from fsset import getDiskPart
import iutil
from product import *

import booty
import checkbootloader

if rhpl.getArch() not in ("s390", "s390x"):
    import block

dosFilesystems = ('FAT', 'fat16', 'fat32', 'ntfs', 'hpfs')

def doesDualBoot():
    if rhpl.getArch() == "i386" or rhpl.getArch() == "x86_64":
        return 1
    return 0

def checkForBootBlock(device):
    fd = os.open(device, os.O_RDONLY)
    buf = os.read(fd, 512)
    os.close(fd)
    if len(buf) >= 512 and \
           struct.unpack("H", buf[0x1fe: 0x200]) == (0xaa55,):
        return True
    return False

# hack and a half
# there's no guarantee that data is written to the disk and grub
# reads both the filesystem and the disk.  suck.
def syncDataToDisk(dev, mntpt, instRoot = "/"):
    import isys
    isys.sync()
    isys.sync()
    isys.sync()

    # and xfs is even more "special" (#117968)
    if isys.readFSType(dev) == "xfs":
        rhpl.executil.execWithRedirect( "/usr/sbin/xfs_freeze",
                                        ["/usr/sbin/xfs_freeze", "-f", mntpt],
                                        stdout = "/dev/tty5",
                                        stderr = "/dev/tty5",
                                        root = instRoot)
        rhpl.executil.execWithRedirect( "/usr/sbin/xfs_freeze",
                                        ["/usr/sbin/xfs_freeze", "-u", mntpt],
                                        stdout = "/dev/tty5",
                                        stderr = "/dev/tty5",
                                        root = instRoot)    

class BootyNoKernelWarning:
    def __init__ (self, value=""):
        self.value = value
        
    def __str__ (self):
        return self.value

class KernelArguments:

    def get(self):
        return self.args

    def set(self, args):
        self.args = args

    def chandevget(self):
        return self.cargs

    def chandevset(self, args):
        self.cargs = args

    def append(self, args):
        if self.args:
            # don't duplicate the addition of an argument (#128492)
            if self.args.find(args) != -1:
                return
            self.args = self.args + " "
        self.args = self.args + "%s" % (args,)
        

    def __init__(self):
        newArgs = []
        cfgFilename = "/tmp/install.cfg"

        if rhpl.getArch() == "s390":
            self.cargs = []
            f = open(cfgFilename)
            for line in f:
                try:
                    (vname,vparm) = line.split('=', 1)
                    vname = vname.strip()
                    vparm = vparm.replace('"','')
                    vparm = vparm.strip()
                    if vname == "DASD":
                        newArgs.append("dasd=" + vparm)
                    if vname == "CHANDEV":
                        self.cargs.append(vparm)
                    if vname == "QETHPARM":
                        self.cargs.append(vparm)
                except Exception, e:
                    pass
            f.close()

        # look for kernel arguments we know should be preserved and add them
        ourargs = ["speakup_synth", "apic", "noapic", "apm", "ide", "noht",
                   "acpi", "video", "pci", "nodmraid", "nompath"]
        for arg in ourargs:
            if not flags.cmdline.has_key(arg):
                continue

            val = flags.cmdline.get(arg, "")
            if val:
                newArgs.append("%s=%s" % (arg, val))
            else:
                newArgs.append(arg)

        self.args = " ".join(newArgs)


class BootImages:
    """A collection to keep track of boot images available on the system.
    Examples would be:
    ('linux', 'Red Hat Linux', 'ext2'),
    ('Other', 'Other', 'fat32'), ...
    """
    def __init__(self):
        self.default = None
        self.images = {}

    def getImages(self):
        """returns dictionary of (label, longlabel, devtype) pairs 
        indexed by device"""
        # return a copy so users can modify it w/o affecting us
        return copy(self.images)


    def setImageLabel(self, dev, label, setLong = 0):
        orig = self.images[dev]
        if setLong:
            self.images[dev] = (orig[0], label, orig[2])
        else:
            self.images[dev] = (label, orig[1], orig[2])            
            
    def setDefault(self, default):
        # default is a device
        self.default = default

    def getDefault(self):
        return self.default

    # XXX this has internal anaconda-ish knowledge.  ick 
    def setup(self, diskSet, fsset):
        devices = {}
        devs = self.availableBootDevices(diskSet, fsset)
        for (dev, type) in devs:
            devices[dev] = 1

        # These partitions have disappeared
        for dev in self.images.keys():
            if not devices.has_key(dev): del self.images[dev]

        # These have appeared
        for (dev, type) in devs:
            if not self.images.has_key(dev):
                if type in dosFilesystems and doesDualBoot():
                    self.images[dev] = ("Other", "Other", type)
                elif type in ("hfs", "hfs+") and rhpl.getPPCMachine() == "PMac":
                    self.images[dev] = ("Other", "Other", type)
                else:
                    self.images[dev] = (None, None, type)


        if not self.images.has_key(self.default):
            entry = fsset.getEntryByMountPoint('/')
            self.default = entry.device.getDevice()
            (label, longlabel, type) = self.images[self.default]
            if not label:
                self.images[self.default] = ("linux", productName, type)

    # XXX more internal anaconda knowledge
    def availableBootDevices(self, diskSet, fsset):
        devs = []
        foundDos = 0
        for (dev, type) in diskSet.partitionTypes():
            if type in dosFilesystems and not foundDos and doesDualBoot():
                import isys
                import partedUtils
                
                part = partedUtils.get_partition_by_name(diskSet.disks, dev)
                if part.native_type not in partedUtils.dosPartitionTypes:
                    continue

                try:
                    bootable = checkForBootBlock('/dev/' + dev)
                    devs.append((dev, type))
                    foundDos = 1
                except Exception, e:
                    pass
            elif ((type == 'ntfs' or type =='hpfs') and not foundDos
                  and doesDualBoot()):
                devs.append((dev, type))
                # maybe questionable, but the first ntfs or fat is likely to
                # be the correct one to boot with XP using ntfs
                foundDos = 1
            elif type in ('hfs', 'hfs+') and rhpl.getPPCMachine() == "PMac":
                import isys
                import partedUtils

                part = partedUtils.get_partition_by_name(diskSet.disks, dev)
                if partedUtils.get_flags(part) != "boot":
                    devs.append((dev, type))

        slash = fsset.getEntryByMountPoint('/')
        if not slash or not slash.device or not slash.fsystem:
            raise ValueError, ("Trying to pick boot devices but do not have a "
                               "sane root partition.  Aborting install.")
        devs.append((slash.device.getDevice(), slash.fsystem.getName()))

        devs.sort()

        return devs



class bootloaderInfo:
    def getConfigFileName(self):
        if not self._configname:
            raise NotImplementedError
        return self._configname
    configname = property(getConfigFileName, None, None, \
                          "bootloader config file name")

    def getConfigFileDir(self):
        if not self._configdir:
            raise NotImplementedError
        return self._configdir
    configdir = property(getConfigFileDir, None, None, \
                         "bootloader config file directory")

    def getConfigFilePath(self):
        return "%s/%s" % (self.configdir, self.configname)
    configfile = property(getConfigFilePath, None, None, \
                          "full path and name of the real config file")

    def setUseGrub(self, val):
        pass

    def useGrub(self):
        return self.useGrubVal

    def setForceLBA(self, val):
        pass
    
    def setPassword(self, val, isCrypted = 1):
        pass

    def getPassword(self):
        pass

    def getDevice(self):
        return self.device

    def setDevice(self, device):
        self.device = device

        (dev, part) = getDiskPart(device)
        if part is None:
            self.defaultDevice = "mbr"
        else:
            self.defaultDevice = "partition"

    def makeInitrd(self, kernelTag):
        return "/boot/initrd%s.img" % kernelTag

    # XXX need to abstract out the requirement for a fsset to be able
    # to get it "on the fly" on a running system as well as being able
    # to get it how we do now from anaconda.  probably by having the
    # first thing in the chain create a "fsset" object that has the
    # dictionary of mounted filesystems since that's what we care about
    def getBootloaderConfig(self, instRoot, fsset, bl, kernelList,
                            chainList, defaultDev):
        images = bl.images.getImages()

        # on upgrade read in the lilo config file
        lilo = LiloConfigFile ()
        self.perms = 0600
        if os.access (instRoot + self.configfile, os.R_OK):
            self.perms = os.stat(instRoot + self.configfile)[0] & 0777
            lilo.read (instRoot + self.configfile)
            os.rename(instRoot + self.configfile,
                      instRoot + self.configfile + '.rpmsave')
        # if it's an absolute symlink, just get it out of our way
        elif (os.path.islink(instRoot + self.configfile) and
              os.readlink(instRoot + self.configfile)[0] == '/'):
            os.rename(instRoot + self.configfile,
                      instRoot + self.configfile + '.rpmsave')            

        # Remove any invalid entries that are in the file; we probably
        # just removed those kernels. 
        for label in lilo.listImages():
            (fsType, sl, path, other) = lilo.getImage(label)
            if fsType == "other": continue

            if not os.access(instRoot + sl.getPath(), os.R_OK):
                lilo.delImage(label)

        lilo.addEntry("prompt", replace = 0)
        lilo.addEntry("timeout", self.timeout or "20", replace = 0)

        rootDev = fsset.getEntryByMountPoint("/").device.getDevice()
        if not rootDev:
            raise RuntimeError, "Installing lilo, but there is no root device"

        if rootDev == defaultDev:
            lilo.addEntry("default", kernelList[0][0])
        else:
            lilo.addEntry("default", chainList[0][0])

        for (label, longlabel, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = self.kernelLocation + "vmlinuz" + kernelTag

            try:
                lilo.delImage(label)
            except IndexError, msg:
                pass

            sl = LiloConfigFile(imageType = "image", path = kernelFile)

            initrd = self.makeInitrd(kernelTag)

            sl.addEntry("label", label)
            if os.access (instRoot + initrd, os.R_OK):
                sl.addEntry("initrd", "%sinitrd%s.img" %(self.kernelLocation,
                                                         kernelTag))
                
            sl.addEntry("read-only")

            append = "%s" %(self.args.get(),)
            realroot = getRootDevName(initrd, fsset, rootDev, instRoot)
            if rootIsDevice(realroot):
                sl.addEntry("root", '/dev/' + rootDev)
            else:
                if len(append) > 0:
                    append = "%s root=%s" %(append,realroot)
                else:
                    append = "root=%s" %(realroot,)
            
            if len(append) > 0:
                sl.addEntry('append', '"%s"' % (append,))
                
            lilo.addImage (sl)

        for (label, longlabel, device) in chainList:
            if ((not label) or (label == "")):
                continue
            try:
                (fsType, sl, path, other) = lilo.getImage(label)
                lilo.delImage(label)
            except IndexError:
                sl = LiloConfigFile(imageType = "other",
                                    path = "/dev/%s" %(device))
                sl.addEntry("optional")

            sl.addEntry("label", label)
            lilo.addImage (sl)

        # Sanity check #1. There could be aliases in sections which conflict
        # with the new images we just created. If so, erase those aliases
        imageNames = {}
        for label in lilo.listImages():
            imageNames[label] = 1

        for label in lilo.listImages():
            (fsType, sl, path, other) = lilo.getImage(label)
            if sl.testEntry('alias'):
                alias = sl.getEntry('alias')
                if imageNames.has_key(alias):
                    sl.delEntry('alias')
                imageNames[alias] = 1

        # Sanity check #2. If single-key is turned on, go through all of
        # the image names (including aliases) (we just built the list) and
        # see if single-key will still work.
        if lilo.testEntry('single-key'):
            singleKeys = {}
            turnOff = 0
            for label in imageNames.keys():
                l = label[0]
                if singleKeys.has_key(l):
                    turnOff = 1
                singleKeys[l] = 1
            if turnOff:
                lilo.delEntry('single-key')

        return lilo

    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf = None):
        if len(kernelList) >= 1:
            config = self.getBootloaderConfig(instRoot, fsset, bl,
                                              kernelList, chainList,
                                              defaultDev)
            config.write(instRoot + self.configfile, perms = self.perms)
        else:
            self.noKernelsWarn(intf)

        return ""

    # XXX in the future we also should do some validation on the config
    # file that's already there
    # XXX concept of the intf isn't very well defined outside of anaconda...
    # probably should just pass back up an error
    def noKernelsWarn(self, intf):
        raise BootyNoKernelWarning

    def getArgList(self):
        args = []

        if self.defaultDevice is None:
            args.append("--location=none")
            return args

        args.append("--location=%s" % (self.defaultDevice,))
        args.append("--driveorder=%s" % (",".join(self.drivelist)))

        if self.args.get():
            args.append("--append=\"%s\"" %(self.args.get()))

        return args

    def writeKS(self, f):
        f.write("bootloader")
        for arg in self.getArgList():
            f.write(" " + arg)
        f.write("\n")

    def createDriveList(self):
        # create a drive list that we can use for drive mappings
        # XXX has anaconda internals knowledge
        import isys
        drives = isys.hardDriveDict().keys()
        drives.sort(isys.compareDrives)

        # now filter out all of the drives without media present
        drives = filter(lambda x: isys.mediaPresent(x), drives)

        return drives

    def updateDriveList(self, sortedList=[]):
        self._drivelist = self.createDriveList()

        # If we're given a sort order, make sure the drives listed in it
        # are put at the head of the drivelist in that order.  All other
        # drives follow behind in whatever order they're found.
        if sortedList != []:
            revSortedList = sortedList
            revSortedList.reverse()

            for i in revSortedList:
                try:
                    ele = self._drivelist.pop(self._drivelist.index(i))
                    self._drivelist.insert(0, ele)
                except:
                    pass

    def _getDriveList(self):
        if self._drivelist is not None:
            return self._drivelist
        self.updateDriveList()
        return self._drivelist
    def _setDriveList(self, val):
        self._drivelist = val
    drivelist = property(_getDriveList, _setDriveList)

    def __init__(self):
        self.args = KernelArguments()
        self.images = BootImages()
        self.device = None
        self.defaultDevice = None  # XXX hack, used by kickstart
        self.useGrubVal = 0      # only used on x86
        self._configdir = None
        self._configname = None
        self.kernelLocation = "/boot/"
        self.forceLBA32 = 0
        self.password = None
        self.pure = None
        self.above1024 = 0
        self.timeout = None

        # this has somewhat strange semantics.  if 0, act like a normal
        # "install" case.  if 1, update lilo.conf (since grubby won't do that)
        # and then run lilo or grub only.
        # XXX THIS IS A HACK.  implementation details are only there for x86
        self.doUpgradeOnly = 0
        self.kickstart = 0

        self._drivelist = None

        if flags.serial != 0:
            options = ""
            device = ""
            console = flags.get("console", "")

            # the options are everything after the comma
            comma = console.find(",")
            if comma != -1:
                options = console[comma:]
                device = console[:comma]
            else:
                device = console

            if not device and rhpl.getArch() != "ia64":
                self.serialDevice = "ttyS0"
                self.serialOptions = ""
            else:
                self.serialDevice = device
                # don't keep the comma in the options
                self.serialOptions = options[1:]

            if self.serialDevice:
                self.args.append("console=%s%s" %(self.serialDevice, options))
                self.serial = 1
                self.timeout = 5
        else:
            self.serial = 0
            self.serialDevice = None
            self.serialOptions = None

        if flags.virtpconsole is not None:
            if flags.virtpconsole.startswith("/dev/"):
                con = flags.virtpconsole[5:]
            else:
                con = flags.virtpconsole
            self.args.append("console=%s" %(con,))


class grubBootloaderInfo(bootloaderInfo):
    def setPassword(self, val, isCrypted = 1):
        if not val:
            self.password = val
            self.pure = val
            return
        
        if isCrypted and self.useGrubVal == 0:
            self.pure = None
            return
        elif isCrypted:
            self.password = val
            self.pure = None
        else:
            salt = "$1$"
            saltLen = 8

            saltchars = string.letters + string.digits + './'
            for i in range(saltLen):
                salt += random.choice(saltchars)

            self.password = crypt.crypt(val, salt)
            self.pure = val
        
    def getPassword (self):
        return self.pure

    def setForceLBA(self, val):
        self.forceLBA32 = val
        
    def setUseGrub(self, val):
        self.useGrubVal = val

    def getPhysicalDevices(self, device):
        # This finds a list of devices on which the given device name resides.
        # Accepted values for "device" are raid1 md devices (i.e. "md0"),
        # physical disks ("hda"), and real partitions on physical disks
        # ("hda1").  Volume groups/logical volumes are not accepted.
        # 
        # XXX this has internal anaconda-ish knowledge.  ick.
        import isys
        import lvm

        if string.split(device, '/', 1)[0] in map (lambda vg: vg[0],
                                                   lvm.vglist()):
            return []
    
        if device.startswith("mapper/luks-"):
            return []

        if device.startswith('md'):
            bootable = 0
            parts = checkbootloader.getRaidDisks(device, 1, stripPart=0)
            parts.sort()
            return parts

        return [device]

    def runGrubInstall(self, instRoot, bootDev, cmds, cfPath):
        if cfPath == "/":
            syncDataToDisk(bootDev, "/boot", instRoot)
        else:
            syncDataToDisk(bootDev, "/", instRoot)

        # copy the stage files over into /boot
        rhpl.executil.execWithRedirect( "/sbin/grub-install",
                                    ["/sbin/grub-install", "--just-copy"],
                                    stdout = "/dev/tty5", stderr = "/dev/tty5",
                                    root = instRoot)

        # really install the bootloader
        for cmd in cmds:
            p = os.pipe()
            os.write(p[1], cmd + '\n')
            os.close(p[1])
            import time

            # FIXME: hack to try to make sure everything is written
            #        to the disk
            if cfPath == "/":
                syncDataToDisk(bootDev, "/boot", instRoot)
            else:
                syncDataToDisk(bootDev, "/", instRoot)

            rhpl.executil.execWithRedirect('/sbin/grub' ,
                                    [ "grub",  "--batch", "--no-floppy",
                                      "--device-map=/boot/grub/device.map" ],
                                    stdin = p[0],
                                    stdout = "/dev/tty5", stderr = "/dev/tty5",
                                    root = instRoot)
            os.close(p[0])

    def installGrub(self, instRoot, bootDevs, grubTarget, grubPath, fsset,
                    target, cfPath):
        args = "--stage2=/boot/grub/stage2 "
        if self.forceLBA32:
            args = "%s--force-lba " % (args,)

        cmds = []
        for bootDev in bootDevs:
            gtPart = self.getMatchingPart(bootDev, grubTarget)
            gtDisk = self.grubbyPartitionName(getDiskPart(gtPart)[0])
            bPart = self.grubbyPartitionName(bootDev)
            cmd = "root %s\n" % (bPart,)

            stage1Target = gtDisk
            if target == "partition":
                stage1Target = self.grubbyPartitionName(gtPart)

            cmd += "install %s%s/stage1 d %s %s/stage2 p %s%s/grub.conf" % \
                (args, grubPath, stage1Target, grubPath, bPart, grubPath)
            cmds.append(cmd)

            self.runGrubInstall(instRoot, bootDev, cmds, cfPath)

    def writeGrub(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfigFile):
        
        images = bl.images.getImages()
        rootDev = fsset.getEntryByMountPoint("/").device.getDevice()

        # XXX old config file should be read here for upgrade

        cf = "%s%s" % (instRoot, self.configfile)
        self.perms = 0600
        if os.access (cf, os.R_OK):
            self.perms = os.stat(cf)[0] & 0777
            os.rename(cf, cf + '.rpmsave')

        grubTarget = bl.getDevice()
        target = "mbr"
        if (grubTarget.startswith('rd/') or grubTarget.startswith('ida/') or
                grubTarget.startswith('cciss/') or
                grubTarget.startswith('sx8/') or
                grubTarget.startswith('mapper/')):
            if grubTarget[-1].isdigit():
                if grubTarget[-2] == 'p' or \
                        (grubTarget[-2].isdigit() and grubTarget[-3] == 'p'):
                    target = "partition"
        elif grubTarget[-1].isdigit() and not grubTarget.startswith('md'):
            target = "partition"
            
        f = open(cf, "w+")

        f.write("# grub.conf generated by anaconda\n")
        f.write("#\n")
        f.write("# Note that you do not have to rerun grub "
                "after making changes to this file\n")

        bootDev = fsset.getEntryByMountPoint("/boot")
        grubPath = "/grub"
        cfPath = "/"
        if not bootDev:
            bootDev = fsset.getEntryByMountPoint("/")
            grubPath = "/boot/grub"
            cfPath = "/boot/"
            f.write("# NOTICE:  You do not have a /boot partition.  "
                    "This means that\n")
            f.write("#          all kernel and initrd paths are relative "
                    "to /, eg.\n")            
        else:
            f.write("# NOTICE:  You have a /boot partition.  This means "
                    "that\n")
            f.write("#          all kernel and initrd paths are relative "
                    "to /boot/, eg.\n")

        bootDevs = self.getPhysicalDevices(bootDev.device.getDevice())
        bootDev = bootDev.device.getDevice()
        
        f.write('#          root %s\n' % self.grubbyPartitionName(bootDevs[0]))
        f.write("#          kernel %svmlinuz-version ro "
                "root=/dev/%s\n" % (cfPath, rootDev))
        f.write("#          initrd %sinitrd-version.img\n" % (cfPath))
        f.write("#boot=/dev/%s\n" % (grubTarget))

        # get the default image to boot... we have to walk and find it
        # since grub indexes by where it is in the config file
        if defaultDev == rootDev:
            default = 0
        else:
            # if the default isn't linux, it's the first thing in the
            # chain list
            default = len(kernelList)

        # keep track of which devices are used for the device.map
        usedDevs = {}

        f.write('default=%s\n' % (default))
        f.write('timeout=%d\n' % (self.timeout or 0))

        if self.serial == 1:
            # grub the 0-based number of the serial console device
            unit = self.serialDevice[-1]
            
            # and we want to set the speed too
            speedend = 0
            for char in self.serialOptions:
                if char not in string.digits:
                    break
                speedend = speedend + 1
            if speedend != 0:
                speed = self.serialOptions[:speedend]
            else:
                # reasonable default
                speed = "9600"
                
            f.write("serial --unit=%s --speed=%s\n" %(unit, speed))
            f.write("terminal --timeout=%s serial console\n" % (self.timeout or 5))
        else:
            # we only want splashimage if they're not using a serial console
            if os.access("%s/boot/grub/splash.xpm.gz" %(instRoot,), os.R_OK):
                f.write('splashimage=%s%sgrub/splash.xpm.gz\n'
                        % (self.grubbyPartitionName(bootDevs[0]), cfPath))
                f.write("hiddenmenu\n")

        for dev in self.getPhysicalDevices(grubTarget):
            usedDevs[dev] = 1
            
        if self.password:
            f.write('password --md5 %s\n' %(self.password))
        
        for (label, longlabel, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = "%svmlinuz%s" % (cfPath, kernelTag)

            initrd = self.makeInitrd(kernelTag)

            f.write('title %s (%s)\n' % (longlabel, version))
            f.write('\troot %s\n' % self.grubbyPartitionName(bootDevs[0]))

            realroot = getRootDevName(initrd, fsset, rootDev, instRoot)
            realroot = " root=%s" %(realroot,)

            if version.endswith("xen0") or (version.endswith("xen") and not os.path.exists("/proc/xen")):
                # hypervisor case
                sermap = { "ttyS0": "com1", "ttyS1": "com2",
                           "ttyS2": "com3", "ttyS3": "com4" }
                if self.serial and sermap.has_key(self.serialDevice) and \
                       self.serialOptions:
                    hvs = "%s=%s" %(sermap[self.serialDevice],
                                    self.serialOptions)
                else:
                    hvs = ""
                if version.endswith("xen0"):
                    hvFile = "%sxen.gz-%s %s" %(cfPath,
                                                version.replace("xen0", ""),
                                                hvs)
                else:
                    hvFile = "%sxen.gz-%s %s" %(cfPath,
                                                version.replace("xen", ""),
                                                hvs)
                f.write('\tkernel %s\n' %(hvFile,))
                f.write('\tmodule %s ro%s' %(kernelFile, realroot))
                if self.args.get():
                    f.write(' %s' % self.args.get())
                f.write('\n')

                if os.access (instRoot + initrd, os.R_OK):
                    f.write('\tmodule %sinitrd%s.img\n' % (cfPath, kernelTag))
            else: # normal kernel
                f.write('\tkernel %s ro%s' % (kernelFile, realroot))
                if self.args.get():
                    f.write(' %s' % self.args.get())
                f.write('\n')

                if os.access (instRoot + initrd, os.R_OK):
                    f.write('\tinitrd %sinitrd%s.img\n' % (cfPath, kernelTag))

        for (label, longlabel, device) in chainList:
            if ((not longlabel) or (longlabel == "")):
                continue
            f.write('title %s\n' % (longlabel))
            f.write('\trootnoverify %s\n' % self.grubbyPartitionName(device))
#            f.write('\tmakeactive\n')
            f.write('\tchainloader +1')
            f.write('\n')
            usedDevs[device] = 1

        f.close()

        if not "/efi/" in cf:
            os.chmod(cf, self.perms)

        try:
            # make symlink for menu.lst (default config file name)
            menulst = "%s%s/menu.lst" % (instRoot, self.configdir)
            if os.access (menulst, os.R_OK):
                os.rename(menulst, menulst + ".rpmsave")
            os.symlink("./grub.conf", menulst)
        except:
            pass

        try:
            # make symlink for /etc/grub.conf (config files belong in /etc)
            etcgrub = "%s%s" % (instRoot, "/etc/grub.conf")
            if os.access (etcgrub, os.R_OK):
                os.rename(etcgrub, etcgrub + ".rpmsave")
            os.symlink(".." + self.configfile, etcgrub)
        except:
            pass
       
        for dev in self.getPhysicalDevices(rootDev) + bootDevs:
            usedDevs[dev] = 1

        if os.access(instRoot + "/boot/grub/device.map", os.R_OK):
            os.rename(instRoot + "/boot/grub/device.map",
                      instRoot + "/boot/grub/device.map.rpmsave")
        if 1: # not os.access(instRoot + "/boot/grub/device.map", os.R_OK):
            f = open(instRoot + "/boot/grub/device.map", "w+")
            f.write("# this device map was generated by anaconda\n")
            devs = usedDevs.keys()
            usedDevs = {}
            for dev in devs:
                drive = getDiskPart(dev)[0]
                if usedDevs.has_key(drive):
                    continue
                usedDevs[drive] = 1
            devs = usedDevs.keys()
            devs.sort()
            for drive in devs:
                # XXX hack city.  If they're not the sort of thing that'll
                # be in the device map, they shouldn't still be in the list.
                if not drive.startswith('md'):
                    f.write("(%s)     /dev/%s\n" % (self.grubbyDiskName(drive),
                                                drive))
            f.close()
        
        sysconf = '/etc/sysconfig/grub'
        if os.access (instRoot + sysconf, os.R_OK):
            self.perms = os.stat(instRoot + sysconf)[0] & 0777
            os.rename(instRoot + sysconf,
                      instRoot + sysconf + '.rpmsave')
        # if it's an absolute symlink, just get it out of our way
        elif (os.path.islink(instRoot + sysconf) and
              os.readlink(instRoot + sysconf)[0] == '/'):
            os.rename(instRoot + sysconf,
                      instRoot + sysconf + '.rpmsave')
        f = open(instRoot + sysconf, 'w+')
        f.write("boot=/dev/%s\n" %(grubTarget,))
        # XXX forcelba never gets read back...
        if self.forceLBA32:
            f.write("forcelba=1\n")
        else:
            f.write("forcelba=0\n")
        f.close()
            
        if not justConfigFile:
            self.installGrub(instRoot, bootDevs, grubTarget, grubPath, fsset, \
                             target, cfPath)

        return ""

    def getMatchingPart(self, bootDev, target):
        bootName, bootPartNum = getDiskPart(bootDev)
        devices = self.getPhysicalDevices(target)
        for device in devices:
            name, partNum = getDiskPart(device)
            if name == bootName:
                return device
        return devices[0]

    def grubbyDiskName(self, name):
        return "hd%d" % self.drivelist.index(name)

    def grubbyPartitionName(self, dev):
        (name, partNum) = getDiskPart(dev)
        if partNum != None:
            return "(%s,%d)" % (self.grubbyDiskName(name), partNum)
        else:
            return "(%s)" %(self.grubbyDiskName(name))
    

    def getBootloaderConfig(self, instRoot, fsset, bl, kernelList,
                            chainList, defaultDev):
        config = bootloaderInfo.getBootloaderConfig(self, instRoot, fsset,
                                                    bl, kernelList, chainList,
                                                    defaultDev)

        liloTarget = bl.getDevice()

        config.addEntry("boot", '/dev/' + liloTarget, replace = 0)
        config.addEntry("map", "/boot/map", replace = 0)
        config.addEntry("install", "/boot/boot.b", replace = 0)
        message = "/boot/message"

        if self.pure is not None and not self.useGrubVal:
            config.addEntry("restricted", replace = 0)
            config.addEntry("password", self.pure, replace = 0)

        if self.serial == 1:
           # grab the 0-based number of the serial console device
            unit = self.serialDevice[-1]
            # FIXME: we should probably put some options, but lilo
            # only supports up to 9600 baud so just use the defaults
            # it's better than nothing :(
            config.addEntry("serial=%s" %(unit,))
        else:
            # message screws up serial console
            if os.access(instRoot + message, os.R_OK):
                config.addEntry("message", message, replace = 0)

        if not config.testEntry('lba32'):
            if self.forceLBA32 or (bl.above1024 and
                                   rhpl.getArch() != "x86_64"):
                config.addEntry("lba32", replace = 0)

        return config

    # this is a hackish function that depends on the way anaconda writes
    # out the grub.conf with a #boot= comment
    # XXX this falls into the category of self.doUpgradeOnly
    def upgradeGrub(self, instRoot, fsset, bl, kernelList, chainList,
                    defaultDev, justConfigFile):
        if justConfigFile:
            return ""

        theDev = None
        for (fn, stanza) in [ ("/etc/sysconfig/grub", "boot="),
                              ("/boot/grub/grub.conf", "#boot=") ]:
            try:
                f = open(instRoot + fn, "r")
            except:
                continue
        
            # the following bits of code are straight from checkbootloader.py
            lines = f.readlines()
            f.close()
            for line in lines:
                if line.startswith(stanza):
                    theDev = checkbootloader.getBootDevString(line)
                    break
            if theDev is not None:
                break
            
        if theDev is None:
            # we could find the dev before, but can't now...  cry about it
            return ""

        # migrate info to /etc/sysconfig/grub
        self.writeSysconfig(instRoot, theDev)

        # more suckage.  grub-install can't work without a valid /etc/mtab
        # so we have to do shenanigans to get updated grub installed...
        # steal some more code above
        bootDev = fsset.getEntryByMountPoint("/boot")
        grubPath = "/grub"
        cfPath = "/"
        if not bootDev:
            bootDev = fsset.getEntryByMountPoint("/")
            grubPath = "/boot/grub"
            cfPath = "/boot/"

        masterBootDev = bootDev.device.getDevice(asBoot = 0)
        if masterBootDev[0:2] == 'md':
            rootDevs = checkbootloader.getRaidDisks(masterBootDev, raidLevel=1,
                            stripPart = 0)
        else:
            rootDevs = [masterBootDev]
            
        if theDev[5:7] == 'md':
            stage1Devs = checkbootloader.getRaidDisks(theDev[5:], raidLevel=1)
        else:
            stage1Devs = [theDev[5:]]

        for stage1Dev in stage1Devs:
            # cross fingers; if we can't find a root device on the same
            # hardware as this boot device, we just blindly hope the first
            # thing in the list works.

            grubbyStage1Dev = self.grubbyPartitionName(stage1Dev)

            grubbyRootPart = self.grubbyPartitionName(rootDevs[0])

            for rootDev in rootDevs:
                testGrubbyRootDev = getDiskPart(rootDev)[0]
                testGrubbyRootDev = self.grubbyPartitionName(testGrubbyRootDev)

                if grubbyStage1Dev == testGrubbyRootDev:
                    grubbyRootPart = self.grubbyPartitionName(rootDev)
                    break
                    
            args = "--stage2=/boot/grub/stage2 "
            cmd ="root %s" % (grubbyRootPart,)
            cmds = [ cmd ]
            cmd = "install %s%s/stage1 d %s %s/stage2 p %s%s/grub.conf" \
                % (args, grubPath, grubbyStage1Dev, grubPath, grubbyRootPart,
                   grubPath)
            cmds.append(cmd)
        
            if not justConfigFile:
                self.runGrubInstall(instRoot, bootDev.device.setupDevice(),
                                    cmds, cfPath)
 
        return ""

    def writeSysconfig(self, instRoot, installDev):
        sysconf = '/etc/sysconfig/grub'
        if not os.access(instRoot + sysconf, os.R_OK):
            f = open(instRoot + sysconf, "w+")
            f.write("boot=%s\n" %(installDev,))
            # XXX forcelba never gets read back at all...
            if self.forceLBA32:
                f.write("forcelba=1\n")
            else:
                f.write("forcelba=0\n")
            f.close()
        
    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        if self.timeout is None and chainList:
            self.timeout = 5

        # XXX HACK ALERT - see declaration above
        if self.doUpgradeOnly:
            if self.useGrubVal:
                self.upgradeGrub(instRoot, fsset, bl, kernelList,
                                 chainList, defaultDev, justConfig)
            return        

        if len(kernelList) < 1:
            self.noKernelsWarn(intf)

        out = self.writeGrub(instRoot, fsset, bl, kernelList, 
                             chainList, defaultDev,
                             justConfig | (not self.useGrubVal))


    def getArgList(self):
        args = bootloaderInfo.getArgList(self)
        
        if self.forceLBA32:
            args.append("--lba32")
        if self.password:
            args.append("--md5pass=%s" %(self.password))
        
        return args

    def __init__(self):
        bootloaderInfo.__init__(self)
        self._configdir = "/boot/grub"
        self._configname = "grub.conf"
        # XXX use checkbootloader to determine what to default to
        self.useGrubVal = 1
        self.kernelLocation = "/boot/"
        self.password = None
        self.pure = None


class efiBootloaderInfo(bootloaderInfo):
    def getBootloaderName(self):
        return self._bootloader
    bootloader = property(getBootloaderName, None, None, \
                          "name of the bootloader to install")

    # XXX wouldn't it be nice to have a real interface to use efibootmgr from?
    def removeOldEfiEntries(self, instRoot):
        p = os.pipe()
        rhpl.executil.execWithRedirect('/usr/sbin/efibootmgr', ["efibootmgr"],
                               root = instRoot, stdout = p[1])
        os.close(p[1])

        c = os.read(p[0], 1)
        buf = c
        while (c):
            c = os.read(p[0], 1)
            buf = buf + c
        os.close(p[0])
        lines = string.split(buf, '\n')
        for line in lines:
            fields = string.split(line)
            if len(fields) < 2:
                continue
            if string.join(fields[1:], " ") == productName:
                entry = fields[0][4:8]
                rhpl.executil.execWithRedirect('/usr/sbin/efibootmgr',
                                       ["efibootmgr", "-b", entry, "-B"],
                                       root = instRoot,
                                       stdout="/dev/tty5", stderr="/dev/tty5")

    def addNewEfiEntry(self, instRoot, fsset):
        bootdev = fsset.getEntryByMountPoint("/boot/efi").device.getDevice()
        if not bootdev:
            bootdev = fsset.getEntryByDeviceName("sda1").device.getDevice()

        link = "%s%s/%s" % (instRoot, "/etc/", self.configname)
        if not os.access(link, os.R_OK):
            os.symlink("../%s" % (self.configfile), link)

        ind = len(bootdev)
        try:
            while (bootdev[ind-1] in string.digits):
                ind = ind - 1
        except IndexError:
            ind = len(bootdev) - 1
            
        bootdisk = bootdev[:ind]
        bootpart = bootdev[ind:]
        if (bootdisk.startswith('ida/') or bootdisk.startswith('cciss/') or
            bootdisk.startswith('rd/') or bootdisk.startswith('sx8/')):
            bootdisk = bootdisk[:-1]

        argv = [ "/usr/sbin/efibootmgr", "-c" , "-w", "-L",
                 productName, "-d", "/dev/%s" % bootdisk,
                 "-p", bootpart, "-l", "\\EFI\\redhat\\" + self.bootloader ]
        rhpl.executil.execWithRedirect(argv[0], argv, root = instRoot,
                               stdout = "/dev/tty5",
                               stderr = "/dev/tty5")

    def installGrub(self, instRoot, bootDevs, grubTarget, grubPath, fsset,
                    target, cfPath):
        if not iutil.isEfi():
            raise EnvironmentError
        self.removeOldEfiEntries(instRoot)
        self.addNewEfiEntry(instRoot, fsset)

    def __init__(self, initialize = True):
        if initialize:
            bootloaderInfo.__init__(self)
        if iutil.isEfi():
            self._configdir = "/boot/efi/EFI/redhat"
            self._configname = "grub.conf"
            self._bootloader = "grub.efi"
            self.useGrubVal = 1
            self.kernelLocation = ""

class x86BootloaderInfo(grubBootloaderInfo, efiBootloaderInfo):
    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        grubBootloaderInfo.write(self, instRoot, fsset, bl, kernelList,
                                 chainList, defaultDev, justConfig, intf)

        # XXX move the lilo.conf out of the way if they're using GRUB
        # so that /sbin/installkernel does a more correct thing
        if self.useGrubVal and os.access(instRoot + '/etc/lilo.conf', os.R_OK):
            os.rename(instRoot + "/etc/lilo.conf",
                      instRoot + "/etc/lilo.conf.anaconda")

    def installGrub(self, *args):
        args = [self] + list(args)
        try:
            apply(efiBootloaderInfo.installGrub, args, {})
        except EnvironmentError:
            apply(grubBootloaderInfo.installGrub, args, {})

    def __init__(self):
        grubBootloaderInfo.__init__(self)
        efiBootloaderInfo.__init__(self, initialize=False)

class ia64BootloaderInfo(efiBootloaderInfo):
    def getBootloaderConfig(self, instRoot, fsset, bl, kernelList,
                            chainList, defaultDev):
        config = bootloaderInfo.getBootloaderConfig(self, instRoot, fsset,
                                                    bl, kernelList, chainList,
                                                    defaultDev)
        # altix boxes need relocatable (#120851)
        config.addEntry("relocatable")

        return config
            
    def writeLilo(self, instRoot, fsset, bl, kernelList, 
                  chainList, defaultDev, justConfig):
        config = self.getBootloaderConfig(instRoot, fsset, bl,
                                          kernelList, chainList, defaultDev)
        config.write(instRoot + self.configfile, perms = 0755)

        return ""
        
    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        if len(kernelList) >= 1:
            out = self.writeLilo(instRoot, fsset, bl, kernelList, 
                                 chainList, defaultDev, justConfig)
        else:
            self.noKernelsWarn(intf)

        self.removeOldEfiEntries(instRoot)
        self.addNewEfiEntry(instRoot, fsset)

    def makeInitrd(self, kernelTag):
        return "/boot/efi/EFI/redhat/initrd%s.img" % kernelTag

    def __init__(self):
        efiBootloaderInfo.__init__(self)
        self._configname = "elilo.conf"
        self._bootloader = "elilo.efi"

class s390BootloaderInfo(bootloaderInfo):
    def getBootloaderConfig(self, instRoot, fsset, bl, kernelList,
                            chainList, defaultDev):
        images = bl.images.getImages()

        # on upgrade read in the lilo config file
        lilo = LiloConfigFile ()
        self.perms = 0600
        if os.access (instRoot + self.configfile, os.R_OK):
            self.perms = os.stat(instRoot + self.configfile)[0] & 0777
            lilo.read (instRoot + self.configfile)
            os.rename(instRoot + self.configfile,
                      instRoot + self.configfile + '.rpmsave')

        # Remove any invalid entries that are in the file; we probably
        # just removed those kernels. 
        for label in lilo.listImages():
            (fsType, sl, path, other) = lilo.getImage(label)
            if fsType == "other": continue

            if not os.access(instRoot + sl.getPath(), os.R_OK):
                lilo.delImage(label)

        rootDev = fsset.getEntryByMountPoint("/").device.getDevice()
        if not rootDev:
            raise RuntimeError, "Installing zipl, but there is no root device"

        if rootDev == defaultDev:
            lilo.addEntry("default", kernelList[0][0])
        else:
            lilo.addEntry("default", chainList[0][0])

        for (label, longlabel, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = self.kernelLocation + "vmlinuz" + kernelTag

            try:
                lilo.delImage(label)
            except IndexError, msg:
                pass

            sl = LiloConfigFile(imageType = "image", path = kernelFile)

            initrd = self.makeInitrd(kernelTag)

            sl.addEntry("label", label)
            if os.access (instRoot + initrd, os.R_OK):
                sl.addEntry("initrd",
                            "%sinitrd%s.img" %(self.kernelLocation, kernelTag))

            sl.addEntry("read-only")
            sl.addEntry("root", '/dev/' + rootDev)
            sl.addEntry("ipldevice", '/dev/' + rootDev[:-1])

            if self.args.get():
                sl.addEntry('append', '"%s"' % self.args.get())
                
            lilo.addImage (sl)

        for (label, longlabel, device) in chainList:
            if ((not label) or (label == "")):
                continue
            try:
                (fsType, sl, path, other) = lilo.getImage(label)
                lilo.delImage(label)
            except IndexError:
                sl = LiloConfigFile(imageType = "other",
                                    path = "/dev/%s" %(device))
                sl.addEntry("optional")

            sl.addEntry("label", label)
            lilo.addImage (sl)

        # Sanity check #1. There could be aliases in sections which conflict
        # with the new images we just created. If so, erase those aliases
        imageNames = {}
        for label in lilo.listImages():
            imageNames[label] = 1

        for label in lilo.listImages():
            (fsType, sl, path, other) = lilo.getImage(label)
            if sl.testEntry('alias'):
                alias = sl.getEntry('alias')
                if imageNames.has_key(alias):
                    sl.delEntry('alias')
                imageNames[alias] = 1

        # Sanity check #2. If single-key is turned on, go through all of
        # the image names (including aliases) (we just built the list) and
        # see if single-key will still work.
        if lilo.testEntry('single-key'):
            singleKeys = {}
            turnOff = 0
            for label in imageNames.keys():
                l = label[0]
                if singleKeys.has_key(l):
                    turnOff = 1
                singleKeys[l] = 1
            if turnOff:
                lilo.delEntry('single-key')

        return lilo

    def writeChandevConf(self, bl, instroot):   # S/390 only 
        cf = "/etc/chandev.conf"
        self.perms = 0644
        if bl.args.chandevget():
            fd = os.open(instroot + "/etc/chandev.conf",
                         os.O_WRONLY | os.O_CREAT)
            os.write(fd, "noauto\n")
            for cdev in bl.args.chandevget():
                os.write(fd,'%s\n' % cdev)
            os.close(fd)
        return ""
        
    
    def writeZipl(self, instRoot, fsset, bl, kernelList, chainList,
                  defaultDev, justConfigFile):
        images = bl.images.getImages()
        rootDev = fsset.getEntryByMountPoint("/").device.getDevice()
        
        cf = '/etc/zipl.conf'
        self.perms = 0600
        if os.access (instRoot + cf, os.R_OK):
            self.perms = os.stat(instRoot + cf)[0] & 0777
            os.rename(instRoot + cf,
                      instRoot + cf + '.rpmsave')

        f = open(instRoot + cf, "w+")        

        f.write('[defaultboot]\n')
        f.write('default=' + kernelList[0][0] + '\n')
        f.write('target=%s\n' % (self.kernelLocation))

        cfPath = "/boot/"
        for (label, longlabel, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = "%svmlinuz%s" % (cfPath, kernelTag)

            initrd = self.makeInitrd(kernelTag)
            f.write('[%s]\n' % (label))
            f.write('\timage=%s\n' % (kernelFile))
            if os.access (instRoot + initrd, os.R_OK):
                f.write('\tramdisk=%sinitrd%s.img\n' %(self.kernelLocation,
                                                     kernelTag))
            realroot = getRootDevName(initrd, fsset, rootDev, instRoot)
            f.write('\tparameters="root=%s' %(realroot,))
            if bl.args.get():
                f.write(' %s' % (bl.args.get()))
            f.write('"\n')

        f.close()

        if not justConfigFile:
            argv = [ "/sbin/zipl" ]
            rhpl.executil.execWithRedirect(argv[0], argv, root = instRoot,
                                   stdout = "/dev/stdout",
                                   stderr = "/dev/stderr")
            
        return ""

    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        out = self.writeZipl(instRoot, fsset, bl, kernelList, 
                             chainList, defaultDev,
                             justConfig | (not self.useZiplVal))
        out = self.writeChandevConf(bl, instRoot)
    
    def __init__(self):
        bootloaderInfo.__init__(self)
        self.useZiplVal = 1      # only used on s390
        self.kernelLocation = "/boot/"
        self.configfile = "/etc/zipl.conf"


class alphaBootloaderInfo(bootloaderInfo):
    def wholeDevice (self, path):
        (device, foo) = getDiskPart(path)
        return device

    def partitionNum (self, path):
        # getDiskPart returns part numbers 0-based; we need it one based
        # *sigh*
        (foo, partitionNumber) = getDiskPart(path)
        return partitionNumber + 1

    def writeAboot(self, instRoot, fsset, bl, kernelList,
                   chainList, defaultDev, justConfig):
        # Get bootDevice and rootDevice
        rootDevice = fsset.getEntryByMountPoint("/").device.getDevice()
        if fsset.getEntryByMountPoint("/boot"):
            bootDevice = fsset.getEntryByMountPoint("/boot").device.getDevice()
        else:
            bootDevice = rootDevice
        bootnotroot = bootDevice != rootDevice

        # If /etc/aboot.conf already exists we rename it
        # /etc/aboot.conf.rpmsave.
        if os.path.isfile(instRoot + self.configfile):
            os.rename (instRoot + self.configfile,
                       instRoot + self.configfile + ".rpmsave")
        
        # Then we create the necessary files. If the root device isn't
        # the boot device, we create /boot/etc/ where the aboot.conf
        # will live, and we create /etc/aboot.conf as a symlink to it.
        if bootnotroot:
            # Do we have /boot/etc ? If not, create one
            if not os.path.isdir (instRoot + '/boot/etc'):
                os.mkdir(instRoot + '/boot/etc', 0755)

            # We install the symlink (/etc/aboot.conf has already been
            # renamed in necessary.)
            os.symlink("../boot" + self.configfile, instRoot + self.configfile)

            cfPath = instRoot + "/boot" + self.configfile
            # Kernel path is set to / because a boot partition will
            # be a root on its own.
            kernelPath = '/'
        # Otherwise, we just need to create /etc/aboot.conf.
        else:
            cfPath = instRoot + self.configfile
            kernelPath = self.kernelLocation

        # If we already have an aboot.conf, rename it
        if os.access (cfPath, os.R_OK):
            self.perms = os.stat(cfPath)[0] & 0777
            os.rename(cfPath, cfPath + '.rpmsave')
                
        # Now we're going to create and populate cfPath.
        f = open (cfPath, 'w+')
        f.write ("# aboot default configurations\n")

        if bootnotroot:
            f.write ("# NOTICE: You have a /boot partition. This means that\n")
            f.write ("#         all kernel paths are relative to /boot/\n")

        # bpn is the boot partition number.
        bpn = self.partitionNum(bootDevice)
        lines = 0

        # We write entries line using the following format:
        # <line><bpn><kernel-name> root=<rootdev> [options]
        # We get all the kernels we need to know about in kernelList.

        for (kernel, tag, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = "%svmlinuz%s" %(kernelPath, kernelTag)

            f.write("%d:%d%s" %(lines, bpn, kernelFile))

            # See if we can come up with an initrd argument that exists
            initrd = self.makeInitrd(kernelTag)
            if os.path.isfile(instRoot + initrd):
                f.write(" initrd=%sinitrd%s.img" %(kernelPath, kernelTag))

            realroot = getRootDevName(initrd, fsset, rootDevice, instRoot)
            f.write(" root=%s" %(realroot,))

            args = self.args.get()
            if args:
                f.write(" %s" %(args,))

            f.write("\n")
            lines = lines + 1

        # We're done writing the file
        f.close ()
        del f

        if not justConfig:
            # Now we're ready to write the relevant boot information. wbd
            # is the whole boot device, bdpn is the boot device partition
            # number.
            wbd = self.wholeDevice (bootDevice)
            bdpn = self.partitionNum (bootDevice)

            # Calling swriteboot. The first argument is the disk to write
            # to and the second argument is a path to the bootstrap loader
            # file.
            args = ("swriteboot", ("/dev/%s" % wbd), "/boot/bootlx")
            rhpl.executil.execWithRedirect ('/sbin/swriteboot', args,
                                    root = instRoot,
                                    stdout = "/dev/tty5",
                                    stderr = "/dev/tty5")

            # Calling abootconf to configure the installed aboot. The
            # first argument is the disk to use, the second argument is
            # the number of the partition on which aboot.conf resides.
            # It's always the boot partition whether it's / or /boot (with
            # the mount point being omitted.)
            args = ("abootconf", ("/dev/%s" % wbd), str (bdpn))
            rhpl.executil.execWithRedirect ('/sbin/abootconf', args,
                                    root = instRoot,
                                    stdout = "/dev/tty5",
                                    stderr = "/dev/tty5")


    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        if len(kernelList) < 1:
            self.noKernelsWarn(intf)

        self.writeAboot(instRoot, fsset, bl, kernelList, 
                        chainList, defaultDev, justConfig)

    def __init__(self):
        bootloaderInfo.__init__(self)
        self.useGrubVal = 0
        self.configfile = "/etc/aboot.conf"
        # self.kernelLocation is already set to what we need.
        self.password = None
        self.pure = None
    

class ppcBootloaderInfo(bootloaderInfo):
    def getBootDevs(self, fs, bl):
        import fsset

        devs = []
        machine = rhpl.getPPCMachine()

        if machine == 'pSeries':
            for entry in fs.entries:
                if isinstance(entry.fsystem, fsset.prepbootFileSystem) \
                        and entry.format:
                    devs.append('/dev/%s' % (entry.device.getDevice(),))
        elif machine == 'PMac':
            for entry in fs.entries:
                if isinstance(entry.fsystem, fsset.applebootstrapFileSystem) \
                        and entry.format:
                    devs.append('/dev/%s' % (entry.device.getDevice(),))

        if len(devs) == 0:
            # Try to get a boot device; bplan OF understands ext3
            if machine == 'Pegasos' or machine == 'Efika':
                entry = fs.getEntryByMountPoint('/boot')
                # Try / if we don't have this we're not going to work
                if not entry:
                    entry = fs.getEntryByMountPoint('/')
                if entry:
                    dev = "/dev/%s" % (entry.device.getDevice(asBoot=1),)
                    devs.append(dev)
            else:
                if bl.getDevice():
                    devs.append("/dev/%s" % bl.getDevice())
        return devs


    def writeYaboot(self, instRoot, fsset, bl, kernelList, 
                  chainList, defaultDev, justConfigFile):

        yabootTarget = string.join(self.getBootDevs(fsset, bl))

        bootDev = fsset.getEntryByMountPoint("/boot")
        if bootDev:
            cf = "/boot/etc/yaboot.conf"
            cfPath = ""
            if not os.path.isdir(instRoot + "/boot/etc"):
                os.mkdir(instRoot + "/boot/etc")
        else:
            bootDev = fsset.getEntryByMountPoint("/")
            cfPath = "/boot"
            cf = "/etc/yaboot.conf"
        bootDev = bootDev.device.getDevice(asBoot = 1)

        f = open(instRoot + cf, "w+")

        f.write("# yaboot.conf generated by anaconda\n\n")
        
        f.write("boot=%s\n" %(yabootTarget,))
        f.write("init-message=\"Welcome to %s!\\nHit <TAB> for boot options\"\n\n"
                % productName)

        (name, partNum) = getDiskPart(bootDev)
        partno = partNum + 1 # 1 based

        f.write("partition=%s\n" %(partno,))

        f.write("timeout=%s\n" % (self.timeout or 80))
        f.write("install=/usr/lib/yaboot/yaboot\n")
        f.write("delay=5\n")
        f.write("enablecdboot\n")
        f.write("enableofboot\n")
        f.write("enablenetboot\n")        

        yabootProg = "/sbin/mkofboot"
        if rhpl.getPPCMachine() == "PMac":
            # write out the first hfs/hfs+ partition as being macosx
            for (label, longlabel, device) in chainList:
                if ((not label) or (label == "")):
                    continue
                f.write("macosx=/dev/%s\n" %(device,))
                break
            
            f.write("magicboot=/usr/lib/yaboot/ofboot\n")

        elif rhpl.getPPCMachine() == "pSeries":
            f.write("nonvram\n")
            f.write("fstype=raw\n")

        else: #  Default non-destructive case for anything else.
            f.write("nonvram\n")
            f.write("mntpoint=/boot/yaboot\n")
            f.write("usemount\n")
            if not os.access(instRoot + "/boot/yaboot", os.R_OK):
                os.mkdir(instRoot + "/boot/yaboot")
            yabootProg = "/sbin/ybin"

        if self.password:
            f.write("password=%s\n" %(self.password,))
            f.write("restricted\n")

        f.write("\n")
        
        rootDev = fsset.getEntryByMountPoint("/").device.getDevice()

        for (label, longlabel, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = "%s/vmlinuz%s" %(cfPath, kernelTag)

            f.write("image=%s\n" %(kernelFile,))
            f.write("\tlabel=%s\n" %(label,))
            f.write("\tread-only\n")

            initrd = self.makeInitrd(kernelTag)
            if os.access(instRoot + initrd, os.R_OK):
                f.write("\tinitrd=%s/initrd%s.img\n" %(cfPath,kernelTag))

            append = "%s" %(self.args.get(),)

            realroot = getRootDevName(initrd, fsset, rootDev, instRoot)
            if rootIsDevice(realroot):
                f.write("\troot=%s\n" %(realroot,))
            else:
                if len(append) > 0:
                    append = "%s root=%s" %(append,realroot)
                else:
                    append = "root=%s" %(realroot,)

            if len(append) > 0:
                f.write("\tappend=\"%s\"\n" %(append,))
            f.write("\n")

        f.close()
        os.chmod(instRoot + cf, 0600)

        # FIXME: hack to make sure things are written to disk
        import isys
        isys.sync()
        isys.sync()
        isys.sync()

        ybinargs = [ yabootProg, "-f", "-C", cf ]
        
        if not flags.test:
            rhpl.executil.execWithRedirect(ybinargs[0],
                                           ybinargs,
                                           stdout = "/dev/tty5",
                                           stderr = "/dev/tty5",
                                           root = instRoot)

        if (not os.access(instRoot + "/etc/yaboot.conf", os.R_OK) and
            os.access(instRoot + "/boot/etc/yaboot.conf", os.R_OK)):
            os.symlink("../boot/etc/yaboot.conf",
                       instRoot + "/etc/yaboot.conf")
        
        return ""

    def setPassword(self, val, isCrypted = 1):
        # yaboot just handles the password and doesn't care if its crypted
        # or not
        self.password = val
        
    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        if len(kernelList) >= 1:
            out = self.writeYaboot(instRoot, fsset, bl, kernelList, 
                                 chainList, defaultDev, justConfig)
        else:
            self.noKernelsWarn(intf)

    def __init__(self):
        bootloaderInfo.__init__(self)
        self.useYabootVal = 1
        self.kernelLocation = "/boot"
        self.configfile = "/etc/yaboot.conf"


class iseriesBootloaderInfo(bootloaderInfo):
    def ddFile(self, inf, of, bs = 4096):
        src = os.open(inf, os.O_RDONLY)
        dest = os.open(of, os.O_WRONLY | os.O_CREAT)
        size = 0

        buf = os.read(src, bs)
        while len(buf) > 0:
            size = size + len(buf)
            os.write(dest, buf)
            buf = os.read(src, bs)

        os.close(src)
        os.close(dest)

        return size
        
    def write(self, instRoot, fsset, bl, kernelList, chainList,
              defaultDev, justConfig, intf):
        if len(kernelList) < 1:
            self.noKernelsWarn(intf)
            return

        # iseries is Weird (tm) -- here's the basic theory 
        # a) have /boot/vmlinitrd-$(version) 
        # b) copy default kernel to PReP partition
        # c) dd default kernel to /proc/iSeries/mf/C/vmlinux
        # d) set cmdline in /boot/cmdline-$(version)
        # e) copy cmdline to /proc/iSeries/mf/C/cmdline
        # f) set default side to 'C' i /proc/iSeries/mf/side
        # g) put default kernel and cmdline on side B too (#91038)
        
        rootDevice = fsset.getEntryByMountPoint("/").device.getDevice()

        # write our command line files
        for (kernel, tag, kernelTag) in kernelList:
            cmdFile = "%scmdline-%s" %(self.kernelLocation, kernelTag)
            initrd = "%sinitrd-%s.img" %(self.kernelLocation, kernelTag)
            realroot = getRootDevName(initrd, fsset, rootDevice, instRoot)
            f = open(instRoot + cmdFile, "w")
            f.write("ro root=%s" %(realroot,))
            if bl.args.get():
                f.write(" %s" %(bl.args.get(),))
            f.write("\n")
            f.close()
            os.chmod(instRoot + cmdFile, 0644)
            
        kernel, tag, kernelTag = kernelList[0]
        kernelFile = "%svmlinitrd-%s" %(self.kernelLocation, kernelTag)

        # write the kernel to the PReP partition since that's what
        # OS/400 will load as NWSSTG
        bootDev = bl.getDevice()
        if bootDev:
            try:
                self.ddFile(instRoot + kernelFile, "%s/dev/%s" %(instRoot,
                                                                 bootDev))
            except Exception, e:
                # FIXME: should this be more fatal
                pass
        else:
            pass


        # now, it's a lot faster to boot if we don't make people go back
        # into OS/400, so set up side C (used by default for NWSSTG) with
        # our current bits
        for side in ("C", "B"):
            wrotekernel = 0
            try:
                self.ddFile(instRoot + kernelFile,
                            "%s/proc/iSeries/mf/%s/vmlinux" %(instRoot, side))
                wrotekernel = 1
            except Exception, e:
                # FIXME: should this be more fatal?
                pass

            if wrotekernel == 1:
                try:
                    # blank it.  ugh.
                    f = open("%s/proc/iSeries/mf/%s/cmdline" %(instRoot, side),
                             "w+")
                    f.write(" " * 255)
                    f.close()
                    
                    self.ddFile("%s/%scmdline-%s" %(instRoot,
                                                    self.kernelLocation,
                                                    kernelTag),
                                "%s/proc/iSeries/mf/%s/cmdline" %(instRoot,
                                                                  side))
                except Exception, e:
                    pass

        f = open(instRoot + "/proc/iSeries/mf/side", "w")
        f.write("C")
        f.close()
        
    def __init__(self):
        bootloaderInfo.__init__(self)
        self.kernelLocation = "/boot/"

class isolinuxBootloaderInfo(bootloaderInfo):
    def __init__(self):
        bootloaderInfo.__init__(self)
        self.kernelLocation = "/boot"
        self.configfile = "/boot/isolinux/isolinux.cfg"

    def write(self, instRoot, fsset, bl, kernelList, chainList,
              defaultDev, justConfig, intf = None):
        if not os.path.isdir(instRoot + "/boot/isolinux"):
            os.mkdir(instRoot + "/boot/isolinux")

        f = open(instRoot + "/boot/isolinux/isolinux.cfg", "w+")
        f.write("# isolinux.cfg generated by anaconda\n\n")

        f.write("prompt 1\n")
        f.write("timeout %s\n" % (self.timeout or 600))

        # FIXME: as this stands, we can really only handle one due to
        # filename length limitations with base iso9660.  fun, fun.
        for (label, longlabel, version) in kernelList:
            # XXX hackity, hack hack hack.  but we need them in a different
            # path for live cd only
            shutil.copy("%s/boot/vmlinuz-%s" %(instRoot, version),
                        "%s/boot/isolinux/vmlinuz" %(instRoot,))
            shutil.copy("%s/boot/initrd-%s.img" %(instRoot, version),
                        "%s/boot/isolinux/initrd.img" %(instRoot,))
            
            # FIXME: need to dtrt for xen kernels with multiboot com32 module
            f.write("label linux\n")
            f.write("\tkernel vmlinuz\n")
            f.write("\tappend initrd=initrd.img,initlive.gz\n")
            f.write("\n")

            break
            
        f.close()
        os.chmod(instRoot + "/boot/isolinux/isolinux.cfg", 0600)

        # copy the isolinux bin
        shutil.copy(instRoot + "/usr/lib/syslinux/isolinux-debug.bin",
                    instRoot + "/boot/isolinux/isolinux.bin")
    
        
class sparcBootloaderInfo(bootloaderInfo):
    def writeSilo(self, instRoot, fsset, bl, kernelList,
                chainList, defaultDev, justConfigFile):

        bootDev = fsset.getEntryByMountPoint("/boot")
        mf = '/silo.message'
        if bootDev:
            cf = "/boot/silo.conf"
            mfdir = '/boot'
            cfPath = ""
            if not os.path.isdir(instRoot + "/boot"):
                os.mkdir(instRoot + "/boot")
        else:
            bootDev = fsset.getEntryByMountPoint("/")
            cf = "/etc/silo.conf"
            mfdir = '/etc'
            cfPath = "/boot"
        bootDev = bootDev.device.getDevice(asBoot = 1)

        f = open(instRoot + mfdir + mf, "w+")
        f.write("Welcome to %s!\nHit <TAB> for boot options\n\n" % productName)
        f.close()
        os.chmod(instRoot + mfdir + mf, 0600)

        f = open(instRoot + cf, "w+")
        f.write("# silo.conf generated by anaconda\n\n")

        f.write("#boot=%s\n" % (bootDev,))
        f.write("message=%s\n" % (mf,))
        f.write("timeout=%s\n" % (self.timeout or 50))

        (name, partNum) = getDiskPart(bootDev)
        partno = partNum + 1
        f.write("partition=%s\n" % (partno,))

        if self.password:
            f.write("password=%s\n" % (self.password,))
            f.write("restricted\n")

        f.write("default=%s\n" % (kernelList[0][0],))
        f.write("\n")

        rootDev = fsset.getEntryByMountPoint("/").device.getDevice()

        for (label, longlabel, version) in kernelList:
            kernelTag = "-" + version
            kernelFile = "%s/vmlinuz%s" % (cfPath, kernelTag)

            f.write("image=%s\n" % (kernelFile,))
            f.write("\tlabel=%s\n" % (label,))
            f.write("\tread-only\n")

            initrd = self.makeInitrd(kernelTag)
            if os.access(instRoot + initrd, os.R_OK):
                f.write("\tinitrd=%s/initrd%s.img\n" % (cfPath, kernelTag))

            append = "%s" % (self.args.get(),)

            realroot = getRootDevName(initrd, fsset, rootDev, instRoot)
            if rootIsDevice(realroot):
                f.write("\troot=%s\n" % (realroot,))
            else:
                if len(append) > 0:
                    append = "%s root=%s" % (append, realroot)
                else:
                    append = "root=%s" % (realroot,)

            if len(append) > 0:
                f.write("\tappend=\"%s\"\n" % (append,))
            f.write("\n")

        f.close()
        os.chmod(instRoot + cf, 0600)

        # FIXME: hack to make sure things are written to disk
        import isys
        isys.sync()
        isys.sync()
        isys.sync()

        backup = "%s/backup.b" % (cfPath,)
        sbinargs = ["/sbin/silo", "-f", "-C", cf, "-S", backup]
        # TODO!!!  FIXME!!!  XXX!!!
        # butil is not defined!!!  - assume this is in rhpl now?
        if butil.getSparcMachine() == "sun4u":
            sbinargs += ["-u"]
        else:
            sbinargs += ["-U"]

        if not flags.test:
            rhpl.executil.execWithRedirect(sbinargs[0],
                                            sbinargs,
                                            stdout = "/dev/tty5",
                                            stderr = "/dev/tty5",
                                            root = instRoot)

        if (not os.access(instRoot + "/etc/silo.conf", os.R_OK) and
            os.access(instRoot + "/boot/etc/silo.conf", os.R_OK)):
            os.symlink("../boot/etc/silo.conf",
                       instRoot + "/etc/silo.conf")

        return ""

    def setPassword(self, val, isCrypted = 1):
        # silo just handles the password unencrypted
        self.password = val

    def write(self, instRoot, fsset, bl, kernelList, chainList,
            defaultDev, justConfig, intf):
        if len(kernelList) >= 1:
            self.writeSilo(instRoot, fsset, bl, kernelList, chainList,
                        defaultDev, justConfig)
        else:
            self.noKernelsWarn(intf)

    def __init__(self):
        bootloaderInfo.__init__(self)
        self.useSiloVal = 1
        self.kernelLocation = "/boot"
        self._configdir = "/etc"
        self._configname = "silo.conf"

###############
# end of boot loader objects... these are just some utility functions used

def rootIsDevice(dev):
    if dev.startswith("LABEL=") or dev.startswith("UUID="):
        return False
    return True

# hackery to determine if we should do root=LABEL=/ or whatnot
# as usual, knows too much about anaconda
def getRootDevName(initrd, fsset, rootDev, instRoot):
    if not os.access(instRoot + initrd, os.R_OK):
        return "/dev/%s" % (rootDev,)

    try:
        rootEntry = fsset.getEntryByMountPoint("/")
        if rootEntry.getUuid() is not None:
            return "UUID=%s" %(rootEntry.getUuid(),)
        elif rootEntry.getLabel() is not None and rootEntry.device.doLabel is not None:
            return "LABEL=%s" %(rootEntry.getLabel(),)
        return "/dev/%s" %(rootDev,)
    except:
        return "/dev/%s" %(rootDev,)