summaryrefslogtreecommitdiffstats
path: root/anaconda
blob: 1c8e5513323a0a53bb0c45fe1785e7e6982dff16 (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
#!/usr/bin/python
#
# anaconda: The Red Hat Linux Installation program
#
# (in alphabetical order...)
#
# Brent Fox <bfox@redhat.com>
# Mike Fulbright <msf@redhat.com>
# Jakub Jelinek <jakub@redhat.com>
# Jeremy Katz <katzj@redhat.com>
# Erik Troan <ewt@rpath.com>
# Matt Wilson <msw@rpath.com>
#
# ... And many others
#
# Copyright 1999-2006 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.
#

# This toplevel file is a little messy at the moment...

import sys, os
from optparse import OptionParser

# keep up with process ID of miniwm if we start it

miniwm_pid = None

# Make sure messages sent through python's warnings module get logged.
def AnacondaShowWarning(message, category, filename, lineno, file=sys.stderr):
    log.warning("%s" % warnings.formatwarning(message, category, filename, lineno))

# start miniWM
def startMiniWM(root='/'):
    (rd, wr) = os.pipe()
    childpid = os.fork()
    if not childpid:
	if os.access("./mini-wm", os.X_OK):
	    cmd = "./mini-wm"
	elif os.access(root + "/usr/bin/mini-wm", os.X_OK):
	    cmd = root + "/usr/bin/mini-wm"
	else:
	    return None
	
	os.dup2(wr, 1)
	os.close(wr)
	args = [cmd, '--display', ':1']
	os.execv(args[0], args)
	sys.exit (1)
    else:
	# We need to make sure that mini-wm is the first client to
	# connect to the X server (see bug #108777).  Wait for mini-wm
	# to write back an acknowledge token.
	os.read(rd, 1)

    return childpid

# startup vnc X server
def startVNCServer(vncpassword="", root='/', vncconnecthost="",
		   vncconnectport=""):
    
    def set_vnc_password(root, passwd, passwd_file):
	(pid, fd) = os.forkpty()

	if not pid:
	    os.execv(root + "/usr/bin/vncpasswd", [root + "/usr/bin/vncpasswd", passwd_file])
	    sys.exit(1)

	# read password prompt
	os.read(fd, 1000)

	# write password
	os.write(fd, passwd + "\n")

	# read challenge again, and newline
	os.read(fd, 1000)
	os.read(fd, 1000)

	# write password again
	os.write(fd, passwd + "\n")

	# read remaining output
	os.read(fd, 1000)

	# wait for status
	try:
	    (pid, status) = os.waitpid(pid, 0)
	except OSError, (errno, msg):
	    print __name__, "waitpid:", msg

	return status

    stdoutLog.info(_("Starting VNC..."))

    # figure out host info
    connxinfo = None
    srvname = None
    try:
	import network

	# try to load /tmp/netinfo and see if we can sniff out network info
	netinfo = network.Network()
	srvname = None
	if netinfo.hostname != "localhost.localdomain":
	    srvname = "%s" % (netinfo.hostname,)
	else:
	    for dev in netinfo.netdevices.keys():
		try:
		    ip = isys.getIPAddress(dev)
		    log.info("ip of %s is %s" %(dev, ip))
		except Exception, e:
		    log.error("Got an exception trying to get the ip addr "
			      "of %s: %s" %(dev, e))
		    continue
		if ip == '127.0.0.1' or ip is None:
		    continue
		srvname = ip
		break

	if srvname is not None:
	    connxinfo = "%s:1" % (srvname,)

    except:
	log.error("Unable to determine VNC server network info")
	
    # figure out product info
    if srvname is not None:
	desktopname = _("%s %s installation on host %s") % (product.productName, product.productVersion, srvname)
    else:
	desktopname = _("%s %s installation") % (product.productName, product.productVersion)

    vncpid = os.fork()

    if not vncpid:
	args = [ root + "/usr/bin/Xvnc", ":1", "-nevershared",
		 "-depth", "16", "-geometry", "800x600",
		 "IdleTimeout=0", "-auth", "/dev/null", "-once",
		 "DisconnectClients=false", "desktop=%s" % (desktopname,)]

	# set passwd if necessary
        if vncpassword != "":
	    try:
		rc = set_vnc_password(root, vncpassword, "/tmp/vncpasswd_file")
	    except Exception, e:
		stdoutLog.error("Unknown exception setting vnc password.")
		log.error("Exception was: %s" %(e,))
		rc = 1

	    if rc:
		stdoutLog.warning(_("Unable to set vnc password - using no password!"))
		stdoutLog.warning(_("Make sure your password is at least 6 characters in length."))
	    else:
		args = args + ["-rfbauth", "/tmp/vncpasswd_file"]
	else:
	    # needed if no password specified
	    args = args + ["SecurityTypes=None",]
			     
	tmplogFile = "/tmp/vncserver.log"
	try:
	    err = os.open(tmplogFile, os.O_RDWR | os.O_CREAT)
	    if err < 0:
		sys.stderr.write("error opening %s\n", tmplogFile)
	    else:
		os.dup2(err, 2)
		os.close(err)
	except:
	    # oh well
	    pass

	os.execv(args[0], args)
	sys.exit (1)

    if vncpassword == "":
	stdoutLog.warning(_("\n\nWARNING!!! VNC server running with NO PASSWORD!\n"
			 "You can use the vncpassword=<password> boot option\n"
			 "if you would like to secure the server.\n\n"))
	
    stdoutLog.info(_("The VNC server is now running."))

    if vncconnecthost != "":
	stdoutLog.info(_("Attempting to connect to vnc client on host %s...") % (vncconnecthost,))
	
	hostarg = vncconnecthost
        if vncconnectport != "":
	    hostarg = hostarg + ":" + vncconnectport
	    
	argv = ["/usr/bin/vncconfig", "-display", ":1", "-connect", hostarg]
	ntries = 0
	while 1:
            output = iutil.execWithCapture(argv[0], argv, catchfd=2)

            if output == "":
                stdoutLog.info(_("Connected!"))
                break
            elif output.startswith("connecting") and output.endswith("failed"):
		ntries += 1
		if ntries > 50:
		    stdoutLog.error(_("Giving up attempting to connect after 50 tries!\n"))
		    if connxinfo is not None:
			stdoutLog.info(_("Please manually connect your vnc client to %s to begin the install.") % (connxinfo,))
		    else:	    
			stdoutLog.info(_("Please manually connect your vnc client to begin the install."))
		    break
		    
		stdoutLog.info(output)
		stdoutLog.info(_("Will try to connect again in 15 seconds..."))
		time.sleep(15)
		continue
	    else:
                stdoutLog.critical(output)
	        sys.exit(1)
    else:
	if connxinfo is not None:
	    stdoutLog.info(_("Please connect to %s to begin the install...") % (connxinfo,))
	else:
	    stdoutLog.info(_("Please connect to begin the install..."))

    os.environ["DISPLAY"]=":1"
    doStartupX11Actions()

# function to handle X startup special issues for anaconda
def doStartupX11Actions():
    global miniwm_pid

    # now start up mini-wm
    try:
	miniwm_pid = startMiniWM()
	log.info("Started mini-wm")
    except:
	miniwm_pid = None
	log.error("Unable to start mini-wm")

    # test to setup dpi
    # cant do this if miniwm didnt run because otherwise when
    # we open and close an X connection in the xutils calls
    # the X server will exit since this is the first X
    # connection (if miniwm isnt running)
    if miniwm_pid is not None:
	import xutils

	try:
	    if xutils.screenWidth() > 640:
		dpi = "96"
	    else:
		dpi = "75"


	    xutils.setRootResource('Xcursor.size', '24')
	    xutils.setRootResource('Xcursor.theme', 'Bluecurve')
	    xutils.setRootResource('Xcursor.theme_core', 'true')

	    xutils.setRootResource('Xft.antialias', '1')
	    xutils.setRootResource('Xft.dpi', dpi)
	    xutils.setRootResource('Xft.hinting', '1')
	    xutils.setRootResource('Xft.hintstyle', 'hintslight')
	    xutils.setRootResource('Xft.rgba', 'none')
	except:
	    sys.stderr.write("X SERVER STARTED, THEN FAILED");
	    raise RuntimeError, "X server failed to start"

def doShutdownX11Actions():
    global miniwm_pid
    
    if miniwm_pid is not None:
	try:
	    os.kill(miniwm_pid, 15)
	    os.waitpid(miniwm_pid, 0)
	except:
	    pass

# handle updates of just a single file in a python package
def setupPythonUpdates():
    import glob

    # get the python version.  first of /usr/lib/python*, strip off the
    # first 15 chars
    pyvers = glob.glob("/usr/lib/python*")
    pyver = pyvers[0][15:]
    
    try:
	os.mkdir("/tmp/updates")
    except:
	pass

    for pypkg in ("rhpl", "yum", "rpmUtils", "urlgrabber", "repomd",
		  "pykickstart", "rhpxl"):
	if os.access("/mnt/source/RHupdates/%s" %(pypkg,), os.X_OK):
	    try:
		os.mkdir("/tmp/updates/%s" %(pypkg,))
	    except:
		pass

	    # symlink the existing ones
	    for f in os.listdir("/mnt/source/RHupdates/%s" %(pypkg,)):
		os.symlink("/mnt/source/RHupdates/%s/%s" %(pypkg, f),
			   "/tmp/updates/%s/%s" %(pypkg, f))

	# get the libdir.  *sigh*
	if os.access("/usr/lib64/python%s/site-packages/%s" %(pyver, pypkg),
		     os.X_OK):
	    libdir = "lib64"
        elif os.access("/usr/lib/python%s/site-packages/%s" %(pyver, pypkg),
                       os.X_OK):
	    libdir = "lib"
	else:
            # If the directory doesn't exist, there's nothing to link over.
            # This happens if we forgot to include one of the above packages
            # in the image, for instance.
            return

	if os.access("/tmp/updates/%s" %(pypkg,), os.X_OK):
	    for f in os.listdir("/usr/%s/python%s/site-packages/%s" %(libdir,
								      pyver,
								      pypkg)):
		if os.access("/tmp/updates/%s/%s" %(pypkg, f), os.R_OK):
		    continue
		elif (f.endswith(".pyc") and
		      os.access("/tmp/updates/%s/%s" %(pypkg, f[:-1]),os.R_OK)):
		    # dont copy .pyc files we are replacing with updates
		    continue
		else:
		    os.symlink("/usr/%s/python%s/site-packages/%s/%s" %(libdir,
									pyver,
									pypkg,
									f),
			       "/tmp/updates/%s/%s" %(pypkg, f))
    
# For anaconda in test mode
if (os.path.exists('isys')):
    sys.path.append('isys')
    sys.path.append('textw')
    sys.path.append('iw')
else:
    sys.path.append('/usr/lib/anaconda')
    sys.path.append('/usr/lib/anaconda/textw')
    sys.path.append('/usr/lib/anaconda/iw')

if (os.path.exists('booty')):
    sys.path.append('booty')
    sys.path.append('booty/edd')
else:
    sys.path.append('/usr/lib/booty')

sys.path.append('/usr/share/system-config-keyboard')
sys.path.append('/usr/share/system-config-date')

try:
    import updates_disk_hook
except ImportError:
    pass

# Set up logging as early as possible.
import logging
from anaconda_log import logger, logLevelMap

log = logging.getLogger("anaconda")
stdoutLog = logging.getLogger("anaconda.stdout")

# pull this in to get product name and versioning
import product

# do this early to keep our import footprint as small as possible
# Python passed my path as argv[0]!
# if sys.argv[0][-7:] == "syslogd":
if len(sys.argv) > 1:
    if sys.argv[1] == "--syslogd":
	from syslogd import Syslogd
	root = sys.argv[2]
	output = sys.argv[3]
	syslog = Syslogd (root, open (output, "a"))
	# this never returns

# this handles setting up RHupdates for pypackages to minimize the set needed
setupPythonUpdates()

import signal, traceback, string, isys, iutil, time
from exception import handleException
import dispatch
import warnings
import rhpl
from flags import flags
from rhpl.translate import _, textdomain, addPoPath

if rhpl.getArch() != "s390" and os.access("/dev/tty3", os.W_OK):
    logger.addFileHandler ("/dev/tty3", log)

warnings.showwarning = AnacondaShowWarning

if os.path.isdir("/mnt/source/RHupdates/po"):
    log.info("adding RHupdates/po")
    addPoPath("/mnt/source/RHupdates/po")
if os.path.isdir("/tmp/updates/po"):
    log.info("adding /tmp/updates/po")    
    addPoPath("/tmp/updates/po")
textdomain("anaconda")

# reset python's default SIGINT handler
signal.signal(signal.SIGINT, signal.SIG_DFL)
signal.signal(signal.SIGSEGV, isys.handleSegv)

# Silly GNOME stuff
if os.environ.has_key('HOME') and not os.environ.has_key("XAUTHORITY"):
    os.environ['XAUTHORITY'] = os.environ['HOME'] + '/.Xauthority'
os.environ['HOME'] = '/tmp'
os.environ['LC_NUMERIC'] = 'C'
os.environ["GCONF_GLOBAL_LOCKS"] = "1"

# In theory, this gets rid of our LVM file descriptor warnings
os.environ["LVM_SUPPRESS_FD_WARNINGS"] = "1"

# we can't let the LD_PRELOAD hang around because it will leak into
# rpm %post and the like.  ick :/
if os.environ.has_key("LD_PRELOAD"):
    del os.environ["LD_PRELOAD"]

# we need to do this really early so we make sure its done before rpm
# is imported
iutil.writeRpmPlatform()

extraModules = []               # XXX: this would be better as a callback
runres_override = False
graphical_failed = 0
instClass = None                # the install class to use

#
# xcfg       - xserver info (?)
# mousehw    - mouseinfo info
# videohw    - videocard info
# monitorhw  - monitor info
#
xcfg = None
monitorhw = None
videohw = None
mousehw = None
kbd = None
vncpassword = ""
vncconnecthost = ""
vncconnectport = ""

def resolution_cb (option, opt_str, value, parser):
    global runres_override
    parser.values.runres = value
    runres_override = True

def rootpath_cb (option, opt_str, value, parser):
    parser.values.rootPath = value
    flags.setupFilesystems = False
    flags.rootpath = True

op = OptionParser()
# Interface
op.add_option("-C", "--cmdline", dest="display_mode", action="store_const", const="c")
op.add_option("-G", "--graphical", dest="display_mode", action="store_const", const="g")
op.add_option("-T", "--text", dest="display_mode", action="store_const", const="t")

# Method of operation
op.add_option("--autostep", action="store_true", default=False)
op.add_option("-d", "--debug", dest="debug", action="store_true", default=False)
op.add_option("--expert", action="store_true", default=False)
op.add_option("--kickstart", dest="ksfile")
op.add_option("-m", "--method", default=None)
op.add_option("--rescue", dest="progmode", action="store_const", const="rescue", default="install")
op.add_option("-r", "--rootpath", action="callback", callback=rootpath_cb, dest="rootPath",
              default="/mnt/sysimage", nargs=1)
op.add_option("-t", "--test", action="store_true", default=False)

# Display
op.add_option("--headless", dest="isHeadless", action="store_true", default=False)
op.add_option("--lowres", dest="resolution", action="store_const", const="640x480")
op.add_option("--nofb")
op.add_option("--resolution", action="callback", callback=resolution_cb, dest="runres",
              default="800x600", nargs=1)
op.add_option("--serial", action="store_true", default=False)
op.add_option("--skipddc", action="store_true", default=False)
op.add_option("--usefbx", dest="useFBX", action="store_true", default=False)
op.add_option("--vesa", dest="forcevesa", action="store_true", default=False)
op.add_option("--virtpconsole")
op.add_option("--vnc", action="store_true", default=False)
op.add_option("--vncconnect")

# Language
op.add_option("--keymap")
op.add_option("--kbdtype")
op.add_option("--lang")

# Obvious
op.add_option("--loglevel")
op.add_option("--syslog")

op.add_option("--noselinux", dest="selinux", action="store_false", default=True)
op.add_option("--selinux", action="store_true")

op.add_option("--nodmraid", dest="dmraid", action="store_false", default=True)
op.add_option("--dmraid", action="store_true")

op.add_option("--noiscsi", dest="iscsi", action="store_false", default=False)
op.add_option("--iscsi", action="store_true")

# Miscellaneous
op.add_option("--module", action="append", default=[])
op.add_option("--nomount", dest="rescue_nomount", action="store_true", default=False)

(opts, args) = op.parse_args()

# Now that we've got arguments, do some extra processing.
if opts.ksfile:
    from kickstart import Kickstart
    instClass = Kickstart(opts.ksfile, opts.serial)

if opts.loglevel and logLevelMap.has_key(opts.loglevel):
    log.setHandlersLevel(logLevelMap[opts.loglevel])

if opts.syslog:
    if opts.syslog.find(":") != -1:
        (host, port) = opts.syslog.split(":")
        logger.addSysLogHandler(log, host, port=int(port))
    else:
        logger.addSysLogHandler(log, opts.syslog)

if opts.method and opts.method[0] == '@':
    # ftp installs pass the password via a file in /tmp so
    # ps doesn't show it
    filename = opts.method[1:]
    opts.method = open(filename, "r").readline()
    opts.method = opts.method[:len(opts.method) - 1]
    os.unlink(filename)

if opts.module:
    for mod in opts.module:
        (path, name) = string.split(mod, ":")
        extraModules.append((path, name))

if opts.test:
    flags.test = 1
    flags.setupFilesystems = 0

if opts.vnc:
    flags.usevnc = 1

    # see if there is a vnc password file
    try:
        pfile = open("/tmp/vncpassword.dat", "r")
        vncpassword=pfile.readline().strip()
        pfile.close()
        os.unlink("/tmp/vncpassword.dat")
    except:
        vncpassword=""
        pass
    
    # check length of vnc password	
    if vncpassword != "" and len(vncpassword) < 6:
        from snack import *
    
        screen = SnackScreen()
        ButtonChoiceWindow(screen, _('VNC Password Error'),
                           _('You need to specify a vnc password of at least 6 characters long.\n\n'
    		     'Press <return> to reboot your system.\n'), 
    		   buttons = (_("OK"),))
        screen.finish()
        sys.exit(0)

if opts.vncconnect:
    cargs = string.split(opts.vncconnect, ":")
    vncconnecthost = cargs[0]
    if len(cargs) > 1:
        if len(cargs[1]) > 0:
	    vncconnectport = cargs[1]

# probing for hardware on an s390 seems silly...
if rhpl.getArch() == "s390":
    opts.isHeadless = True

# setup links required for all install types
for i in ( "services", "protocol", "nsswitch.conf", "joe", "selinux", "libuser.conf"):
    try:
	os.symlink ("../mnt/runtime/etc/" + i, "/etc/" + i)
    except:
	pass

#
# must specify install, rescue mode
#

if opts.progmode == "rescue":
    if not opts.method:
	sys.stderr.write('--method required for rescue mode\n')
	sys.exit(1)

    import rescue, instdata
    
    id = instdata.InstallData([], "fd0", opts.method, opts.display_mode)
    rescue.runRescue(opts.rootPath, not opts.rescue_nomount, id)

    # shouldn't get back here
    sys.exit(1)
else:
    if not opts.method:
	sys.stderr.write('no install method specified\n')
	sys.exit(1)

#
# Here we have a hook to pull in second half of kickstart file via https
# if desired.
#
if opts.ksfile:
    from kickstart import pullRemainingKickstartConfig, KickstartError
    from kickstart import VNCHandlers
    from pykickstart.data import KickstartData
    from pykickstart.parser import KickstartParser

    try:
	rc = pullRemainingKickstartConfig(opts.ksfile)
    except KickstartError, msg:
	rc = msg
    except:
	rc = _("Unknown Error")

    if rc is not None:
	stdoutLog.critical(_("Error pulling second part of kickstart config: %s!") % rc)
	sys.exit(1)

    # now see if they enabled vnc via the kickstart file. Note that command
    # line options for password, connect host and port override values in
    # kickstart file
    ksdata = KickstartData()
    ksparser = KickstartParser(ksdata, VNCHandlers(ksdata),
                               missingIncludeIsFatal=False)
    ksparser.readKickstart(opts.ksfile)

    ksusevnc = ksdata.vnc["enabled"]

    if ksusevnc:
	flags.usevnc = 1

	ksvncpasswd = ksdata.vnc["password"]
	ksvnchost = ksdata.vnc["host"]
	ksvncport = ksdata.vnc["port"]

	if vncpassword == "":
	    vncpassword = ksvncpasswd

	if vncconnecthost == "":
	    vncconnecthost = ksvnchost

	if vncconnectport == "":
	    vncconnectport = ksvncport

#
# Determine install method - GUI or TUI
#
# use GUI by default except for install methods that were traditionally
# text based due to the requirement of a small stage 2
#
# if display_mode wasnt set by command line parameters then set default
#

if not opts.display_mode:
    if (opts.method and
	opts.method.startswith('ftp://') or
	opts.method.startswith('http://')):
	opts.display_mode = 't'
    else:
	opts.display_mode = 'g'

if opts.debug:
    import pdb
    pdb.set_trace()

# let people be stupid
## # don't let folks do anything stupid on !s390
## if (not flags.test and os.getpid() > 90 and flags.setupFilesystems and
##     not rhpl.getArch() == "s390"):
##     sys.stderr.write(
##         "You're running me on a live system! that's incredibly stupid.\n")
##     sys.exit(1)

import isys
import instdata
import floppy
import vnc

if not opts.isHeadless:
    try:
	import xsetup
	import rhpxl.xhwstate as xhwstate
        import rhpxl.monitor
    except ImportError:
	opts.isHeadless = 1
import rhpl.keyboard as keyboard

log.info("Display mode = %s", opts.display_mode)
log.info("Method = %s", opts.method)

#
# override display mode if machine cannot nicely run X
#
if (not flags.test):
    if (iutil.memInstalled() < isys.MIN_GUI_RAM):
	stdoutLog.warning(_("You do not have enough RAM to use the graphical "
			    "installer.  Starting text mode."))
	opts.display_mode = 't'
	time.sleep(2)


if iutil.memInstalled() < isys.MIN_RAM:
    from snack import *

    screen = SnackScreen()
    ButtonChoiceWindow(screen, _('Fatal Error'),
			_('You do not have enough RAM to install %s '
			  'on this machine.\n'
			  '\n'
			  'Press <return> to reboot your system.\n')
		       %(product.productName,), 
		       buttons = (_("OK"),))
    screen.finish()
    sys.exit(0)

# create character device nodes if we're not running in test mode - have
# to do this early sine it's used for Synaptics, etc.
if not flags.test:
    iutil.makeCharDeviceNodes()

#
# if no instClass declared by user figure it out based on other cmdline args
#
if not instClass:
    from installclass import DefaultInstall, availableClasses
    instClass = DefaultInstall(flags.expert)

    allavail = availableClasses(showHidden = 1)
    avail = availableClasses(showHidden = 0)
    if len(avail) == 1:
	(cname, cobject, clogo) = avail[0]
	log.info("%s is only installclass, using it" %(cname,))
	instClass = cobject(flags.expert)
    elif len(allavail) == 1:
	(cname, cobject, clogo) = allavail[0]
	log.info("%s is only installclass, using it" %(cname,))
	instClass = cobject(flags.expert)

# this lets install classes force text mode instlls
if instClass.forceTextMode:
    stdoutLog.info(_("Install class forcing text mode installation"))
    opts.display_mode = 't'

#
# find out what video hardware is available to run installer 
#

# XXX kind of hacky - need to remember if we're running on an existing
#                     X display later to avoid some initilization steps
if os.environ.has_key('DISPLAY') and opts.display_mode == 'g':
    x_already_set = 1
else:
    x_already_set = 0

if not opts.isHeadless:
    #
    # Probe what is available for X and setup a hardware state
    #
    # try to probe interesting hw
    import rhpxl.xserver as xserver
    skipddcprobe = (opts.skipddc or (x_already_set and flags.test))
    skipmouseprobe = not (not os.environ.has_key('DISPLAY') or flags.setupFilesystems)

    (videohw, monitorhw, mousehw) = xserver.probeHW(skipDDCProbe=skipddcprobe,
						    skipMouseProbe=skipmouseprobe,
                                                    forceVesa=opts.forcevesa)
    # if the len(videocards) is zero, then let's assume we're isHeadless
    if len(videohw.videocards) == 0:
	stdoutLog.info (_("No video hardware found, assuming headless"))
	videohw = None
	monitorhw = None
	mousehw = None
	opts.isHeadless = 1
    else:
	# setup a X hw state for use later with configuration.  
	try:
	    xcfg = xhwstate.XF86HardwareState(defcard=videohw,
					      defmon=monitorhw)
	except Exception, e:
	    stdoutLog.error (_("Unable to instantiate a X hardware state object."))
	    xcfg = None
else:
    videohw = None
    monitorhw = None
    mousehw = None
    xcfg = None

# keyboard
kbd = keyboard.Keyboard()
if opts.keymap:
    kbd.set(opts.keymap)

#
# delay to let use see status of attempt to probe hw 
#
time.sleep(3)


#
# now determine if we're going to run in GUI or TUI mode
#
# if no X server, we have to use text mode
if not (flags.test or flags.rootpath) and (rhpl.getArch() != "s390" and not os.access("/mnt/runtime/usr/bin/Xorg", os.X_OK)):
     stdoutLog.warning(_("Graphical installation not available...  "
			 "Starting text mode."))
     time.sleep(2)
     opts.display_mode = 't'

if opts.isHeadless: # s390/iSeries checks
    if opts.display_mode == 'g' and not (os.environ.has_key('DISPLAY') or
				         flags.usevnc):
	stdoutLog.warning(_("DISPLAY variable not set. Starting text mode!"))
	opts.display_mode = 't'
	graphical_failed = 1
	time.sleep(2)

# if DISPLAY not set either vnc server failed to start or we're not
# running on a redirected X display, so start local X server
if opts.display_mode == 'g' and not os.environ.has_key('DISPLAY') and not flags.usevnc:
    modes = rhpxl.monitor.Modes()

    if iutil.getPPCMachine() == "PMac":
	opts.runres = xhwstate.get_valid_resolution(videohw, monitorhw, opts.runres,
					       modes, runres_override, onPMac=True)
    else:
	opts.runres = xhwstate.get_valid_resolution(videohw, monitorhw, opts.runres,
					       modes, runres_override)

    # make sure we can write log to ramfs
    if os.access("/tmp/ramfs", os.W_OK):
	xlogfile = "/tmp/ramfs/X.log"
    else:
	xlogfile = None

    xsetup_failed = False
    try:
	xcfg = xserver.startX(opts.runres, videohw, monitorhw, mousehw, kbd,
			      logfile = xlogfile,
			      xStartedCB = doStartupX11Actions,
			      xQuitCB = doShutdownX11Actions, useFB = opts.useFBX)
    except RuntimeError:
	xsetup_failed = True

    if xsetup_failed:
	stdoutLog.warning(" X startup failed, falling back to text mode")
	opts.display_mode = 't'
	graphical_failed = 1
	time.sleep(2)

if opts.display_mode == 't' and graphical_failed and not opts.ksfile:
    ret = vnc.askVncWindow()
    if ret != -1:
	opts.display_mode = 'g'
	flags.usevnc = 1
	if ret is not None:
	    vncpassword = ret

# if they want us to use VNC do that now
if opts.display_mode == 'g' and flags.usevnc:
    pidfile = "/tmp/vncshell.pid"

    def addpid(pidnum):
	pf = open(pidfile, "a")
	pf.write("%s\n" %(pidnum))
	pf.close()

    def removepid(pidnum):
	pf = open(pidfile, "r")
	pidlist = pf.readlines()
	pf.close()

	pf = open(pidfile, "w")
	for pid in pidlist:
	    if not int(pid) == pidnum:
	        pf.write("%s" %(pid))
	pf.close()

    # dont run vncpassword if in test mode
    if flags.test:
	vncpassword = ""
	
    startVNCServer(vncpassword=vncpassword,
		   vncconnecthost=vncconnecthost,
		   vncconnectport=vncconnectport)

    child = os.fork()
    if child == 0:
	def conthandler(signum, frame):
	    print "\n"

	signal.signal(signal.SIGCONT, conthandler)

	# wait for parent to write pid (parent will send SIGCONT)
	signal.pause()

	while 1:
	    print _("Press <enter> for a shell")
	    sys.stdin.readline()

	    shpid = os.fork()
	    if shpid == 0:
		for p in ('/mnt/source/RHupdates/pyrc.py', \
			'/tmp/updates/pyrc.py', \
			'/usr/lib/anaconda-runtime/pyrc.py'):
		    if os.access(p, os.R_OK|os.X_OK):
			os.environ['PYTHONSTARTUP'] = p
			break
		os.execv("/bin/sh", ["/bin/sh"])
	    else:
	        addpid(shpid)
	        os.waitpid(shpid, 0)
	        removepid(shpid)
    else:
	addpid(child)
	os.kill(child, signal.SIGCONT)


#
# setup links required by graphical mode if installing and verify display mode
#
if (opts.display_mode == 'g'):
    stdoutLog.info (_("Starting graphical installation..."))
    if not flags.test and flags.setupFilesystems:
	for i in ( "imrc", "im_palette.pal", "gtk-2.0", "pango", "fonts",
		   "fb.modes"):
	    try:
		if os.path.exists("/mnt/runtime/etc/%s" %(i,)):
		    os.symlink ("../mnt/runtime/etc/" + i, "/etc/" + i)
	    except:
		pass

    try:
        from gui import InstallInterface
    except Exception, e:
        stdoutLog.error("Exception starting GUI installer: %s" %(e,))
        if flags.test:
            sys.exit(1)
        # if we're not going to really go into GUI mode, we need to get
        # back to vc1 where the text install is going to pop up.
        if not x_already_set:
            isys.vtActivate (1)
        stdoutLog.warning("GUI installer startup failed, falling back to text mode.")
        opts.display_mode = 't'
        if 'DISPLAY' in os.environ.keys():
            del os.environ['DISPLAY']
        time.sleep(2)

if (opts.display_mode == 't'):
    from text import InstallInterface

if (opts.display_mode == 'c'):
    from cmdline import InstallInterface

if opts.display_mode == "t":
    if not os.environ.has_key("LANG"):
        os.environ["LANG"] = "en_US.UTF-8"

# go ahead and set up the interface
intf = InstallInterface ()

# imports after setting up the path
if opts.method:
    if opts.method.startswith('cdrom://'):
	from image import CdromInstallMethod
	methodobj = CdromInstallMethod(opts.method, opts.rootPath, intf)
    elif opts.method.startswith('nfs:/'):
	from image import NfsInstallMethod
	methodobj = NfsInstallMethod(opts.method, opts.rootPath, intf)
    elif opts.method.startswith('nfsiso:/'):
	from image import NfsIsoInstallMethod
	methodobj = NfsIsoInstallMethod(opts.method, opts.rootPath, intf)
    elif opts.method.startswith('ftp://') or opts.method.startswith('http://'):
	from urlinstall import UrlInstallMethod
	methodobj = UrlInstallMethod(opts.method, opts.rootPath, intf)
    elif opts.method.startswith('hd://'):
        from harddrive import HardDriveInstallMethod
        methodobj = HardDriveInstallMethod(opts.method, opts.rootPath, intf)
    else:
        intf.messageWindow(_("Unknown install method"),
                           _("You have specified an install method "
                             "which isn't supported by anaconda."))
	log.critical (_("unknown install method: %s"), opts.method)
	sys.exit(1)

from yuminstall import YumBackend 
backend = YumBackend(methodobj, opts.rootPath)
floppyDevice = floppy.probeFloppyDevice()

# create device nodes for detected devices if we're not running in test mode
if not flags.test and flags.setupFilesystems:
    iutil.makeDriveDeviceNodes()

id = instClass.installDataClass(extraModules, floppyDevice, opts.method, opts.display_mode, backend)

id.x_already_set = x_already_set

if mousehw:
    id.setMouse(mousehw)

if videohw:
    id.setVideoCard(videohw)

if monitorhw:
    id.setMonitor(monitorhw)

#
# not sure what to do here - somehow we didnt detect anything
#
if xcfg is None and not opts.isHeadless:
    try:
	xcfg = xhwstate.XF86HardwareState()
    except Exception, e:
	stdoutLog.error (_("Unable to instantiate a X hardware state object."))
	xcfg = None

if xcfg is not None:
    xsetup = xsetup.XSetup(xcfg)

    # HACK - if user overrides resolution then use it and disable
    #	     choosing a sane default for them
    if runres_override:
	xsetup.imposed_sane_default = 1
	
    id.setXSetup(xsetup)

if kbd:
    id.setKeyboard(kbd)

id.setDisplayMode(opts.display_mode)
instClass.setInstallData(id, intf)

# We need to copy the VNC-related kickstart stuff into the new ksdata
if opts.ksfile is not None:
    instClass.ksdata.vnc = ksdata.vnc

dispatch = dispatch.Dispatcher(intf, id, methodobj, opts.rootPath, backend)

if opts.lang:
    dispatch.skipStep("language", permanent = 1)
    instClass.setLanguage(id, opts.lang)
    instClass.setLanguageDefault(id, opts.lang)

if opts.keymap:
    dispatch.skipStep("keyboard", permanent = 1)
    instClass.setKeyboard(id, opts.keymap)

# Skip the disk options in rootpath mode
if flags.rootpath:
    dispatch.skipStep("partitionobjinit", permanent = 1)
    dispatch.skipStep("parttype", permanent = 1)
    dispatch.skipStep("autopartitionexecute", permanent = 1)
    dispatch.skipStep("partition", permanent = 1)
    dispatch.skipStep("partitiondone", permanent = 1)
    dispatch.skipStep("bootloadersetup", permanent = 1)
    dispatch.skipStep("bootloader", permanent = 1)
    dispatch.skipStep("bootloaderadvanced", permanent = 1)
    dispatch.skipStep("upgbootloader", permanent = 1)
    dispatch.skipStep("instbootloader", permanent = 1)

# set up the headless case
if opts.isHeadless == 1:
    id.setHeadless(opts.isHeadless)
    instClass.setAsHeadless(dispatch, opts.isHeadless)

instClass.setSteps(dispatch)

# comment out the next line to make exceptions non-fatal
sys.excepthook = lambda type, value, tb, dispatch=dispatch, intf=intf: handleException(dispatch, intf, (type, value, tb))

try:
    intf.run(id, dispatch)
except SystemExit, code:
    intf.shutdown()
except:
    handleException(dispatch, intf, sys.exc_info())

if opts.ksfile is not None and instClass.ksdata.reboot["eject"] == True:
    isys.flushDriveDict()
    for drive in isys.cdromList():
        log.info("attempting to eject %s" % drive)
        isys.ejectCdrom(drive)

del intf