#!/usr/bin/python
#
# anaconda: The Red Hat Linux Installation program
#
# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
# Red Hat, Inc.  All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): Brent Fox <bfox@redhat.com>
#            Mike Fulbright <msf@redhat.com>
#            Jakub Jelinek <jakub@redhat.com>
#            Jeremy Katz <katzj@redhat.com>
#            Chris Lumens <clumens@redhat.com>
#            Paul Nasrat <pnasrat@redhat.com>
#            Erik Troan <ewt@rpath.com>
#            Matt Wilson <msw@rpath.com>
#

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

import sys, os, re, time, subprocess
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

# function to handle X startup special issues for anaconda
def doStartupX11Actions(runres="800x600"):
    global miniwm_pid

    if not flags.test and flags.setupFilesystems:
        setupGraphicalLinks()

    # 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")

    # 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:
        try:
            isys.vtActivate(6)
            iutil.execWithRedirect("xrandr", ["-s", runres], searchPath=1,
                                   stdout="/dev/tty5", stderr="/dev/tty5")
            time.sleep(5)
        except Exception, e:
            log.error("Exception when running xrandr: %s" % str(e))


    if miniwm_pid is not None:
        import xutils
        import gtk

        try:
            i = gtk.Invisible()
            i.selection_owner_set("_ANACONDA_MINI_WM_RUNNING")

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

	    xutils.setRootResource('Xft.antialias', '1')
	    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", "pykickstart"):
        # 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.
            continue

        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))

def parseOptions():
    def resolution_cb (option, opt_str, value, parser):
        parser.values.runres = value

    def rootpath_cb (option, opt_str, value, parser):
        parser.values.rootPath = os.path.abspath(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")

    # Network
    op.add_option("--noipv4", action="store_true", default=False)
    op.add_option("--noipv6", action="store_true", default=False)

    # 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("--kickstart", dest="ksfile")
    op.add_option("--rescue", dest="rescue", action="store_true", default=False)
    op.add_option("-r", "--rootpath", action="callback", callback=rootpath_cb, dest="rootPath",
                  default="/mnt/sysimage", nargs=1, type="string")
    op.add_option("-t", "--test", action="store_true", default=False)
    op.add_option("--targetarch", dest="targetArch", nargs=1, type="string")

    op.add_option("-m", "--method", dest="method", default=None)
    op.add_option("--repo", dest="method", default=None)
    op.add_option("--stage2", dest="stage2", default=None)

    op.add_option("--liveinst", action="store_true", default=False)

    # Display
    op.add_option("--headless", dest="isHeadless", action="store_true", default=False)
    op.add_option("--lowres", dest="runres", action="store_const", const="640x480")
    op.add_option("--nofb")
    op.add_option("--resolution", action="callback", callback=resolution_cb, dest="runres",
                  default="800x600", nargs=1, type="string")
    op.add_option("--serial", action="store_true", default=False)
    op.add_option("--usefbx", dest="xdriver", action="store_const", const="fbdev")
    op.add_option("--virtpconsole")
    op.add_option("--vnc", action="store_true", default=False)
    op.add_option("--vncconnect")
    op.add_option("--xdriver", dest="xdriver", action="store", type="string", default=None)

    # 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("--nompath", dest="mpath", action="store_false", default=True)
    op.add_option("--mpath", action="store_true")

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

    op.add_option("--noibft", dest="ibft", action="store_false", default=True)
    op.add_option("--ibft", 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)
    op.add_option("--updates", dest="updateSrc", action="store", type="string")
    op.add_option("--dogtail", dest="dogtail",   action="store", type="string")

    return op.parse_args()

def setVNCFromKickstart(opts):
    from kickstart import KickstartError, VNCHandler
    from pykickstart.parser import KickstartParser, preprocessKickstart

    global vncS

    try:
        opts.ksfile = preprocessKickstart(opts.ksfile)
    except KickstartError, msg:
        stdoutLog.critical(_("Error processing %%ksappend lines: %s") % e)
        sys.exit(1)
    except Exception, e:
        stdoutLog.critical(_("Unknown error processing %%ksappend lines: %s") % e)
        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
    handler = VNCHandler()
    ksparser = KickstartParser(handler, missingIncludeIsFatal=False)

    # We don't have an intf by now so the best we can do is just print the
    # exception out.
    try:
        ksparser.readKickstart(opts.ksfile)
    except KickstartError, e:
        print _("The following error was found while parsing your "
                "kickstart configuration:\n\n%s") % e
        sys.exit(1)

    if handler.vnc.enabled:
        flags.usevnc = 1

        if vncS.password == "":
            vncS.password = handler.vnc.password

        if vncS.vncconnecthost == "":
            vncS.vncconnecthost = handler.vnc.host

        if vncS.vncconnectport == "":
            vncS.vncconnectport = handler.vnc.port

    from pykickstart.constants import DISPLAY_MODE_GRAPHICAL
    if handler.displaymode.displayMode!=DISPLAY_MODE_GRAPHICAL and handler.displaymode.displayMode!=None:
            flags.vncquestion = False

    return handler.vnc

def setRescueModeFromKickstart(opts):
    from kickstart import KickstartError, RescueHandler
    from pykickstart.parser import KickstartParser, preprocessKickstart

    try:
        opts.ksfile = preprocessKickstart(opts.ksfile)
    except KickstartError, msg:
        stdoutLog.critical(_("Error processing %%ksappend lines: %s") % e)
        sys.exit(1)
    except Exception, e:
        stdoutLog.critical(_("Unknown error processing %%ksappend lines: %s") % e)
        sys.exit(1)

    # now see if they enabled rescue mode via the kickstart file. 
    handler = RescueHandler()
    ksparser = KickstartParser(handler, missingIncludeIsFatal=False)

    # We don't have an intf by now so the best we can do is just print the
    # exception out.
    try:
        ksparser.readKickstart(opts.ksfile)
    except KickstartError, e:
        print _("The following error was found while parsing your "
                "kickstart configuration:\n\n%s") % e
        sys.exit(1)

    # True or False
    return handler.rescue.rescue

def setupPythonPath():
    # For anaconda in test mode
    if (os.path.exists('isys')):
        sys.path.insert(0, 'isys')
        sys.path.insert(0, 'textw')
        sys.path.insert(0, 'iw')
    else:
        haveUpdates = False
        for ndx in range(len(sys.path)-1, -1, -1):
            if sys.path[ndx].endswith('updates'):
                haveUpdates = True
                break

        if haveUpdates:
            sys.path.insert(ndx+1, '/usr/%s/anaconda' % sys.lib)
            sys.path.insert(ndx+2, '/usr/%s/anaconda/textw' % sys.lib)
            sys.path.insert(ndx+3, '/usr/%s/anaconda/iw' % sys.lib)
        else:
            sys.path.insert(0, '/usr/%s/anaconda' % sys.lib)
            sys.path.insert(1, '/usr/%s/anaconda/textw' % sys.lib)
            sys.path.insert(2, '/usr/%s/anaconda/iw' % sys.lib)

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

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

def addPoPath(dir):
    """ Looks to see what translations are under a given path and tells
    the gettext module to use that path as the base dir """
    for d in os.listdir(dir):
        if not os.path.isdir("%s/%s" %(dir,d)):
            continue
        if not os.path.exists("%s/%s/LC_MESSAGES" %(dir,d)):
            continue
        for basename in os.listdir("%s/%s/LC_MESSAGES" %(dir,d)):
            if not basename.endswith(".mo"):
                continue
            log.info("setting %s as translation source for %s" %(dir, basename[:-3]))
            gettext.bindtextdomain(basename[:-3], dir)

def setupTranslations():
    if os.path.isdir("/tmp/updates/po"):
        addPoPath("/tmp/updates/po")
    gettext.textdomain("anaconda")

def setupEnvironment():
    # 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"

    # make sure we have /sbin and /usr/sbin in our path
    os.environ["PATH"] += ":/sbin:/usr/sbin"

    # 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"]

def setupLoggingFromOpts(opts):
    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)

def getInstClass():
    from installclass import DefaultInstall
    return DefaultInstall()

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

def runVNC():
    # dont run vncpassword if in test mode
    global vncS
    if flags.test:
        vncS.password = ""

    vncS.startServer()

    child = os.fork()
    if child == 0:
        for p in ('/tmp/updates/pyrc.py', \
                '/usr/%s/anaconda-runtime/pyrc.py' % sys.lib):
            if os.access(p, os.R_OK|os.X_OK):
                os.environ['PYTHONSTARTUP'] = p
                break

        while True:
            # s390/s390x are the only places we /really/ need a shell on tty1,
            # and everywhere else this just gets in the way of pdb.  But we
            # don't want to return, because that'll return try to start X
            # a second time.
            if iutil.isConsoleOnVirtualTerminal():
                    time.sleep(10000)
            else:
                    print _("Press <enter> for a shell")
                    sys.stdin.readline()
                    iutil.execConsole()

def checkMemory(opts):
    if iutil.memInstalled() < isys.MIN_RAM:
        from snack import SnackScreen, ButtonChoiceWindow

        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)

    # override display mode if machine cannot nicely run X
    if not flags.test:
        if opts.display_mode not in ('t', 'c') and 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)

def setupGraphicalLinks():
    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

class Anaconda:
    def __init__(self):
        self.intf = None
        self.dir = None
        self.id = None
        self.methodstr = None
        self.stage2 = None
        self.backend = None
        self.rootPath = None
        self.dispatch = None
        self.isKickstart = False
        self.rescue_mount = True
        self.rescue = False
        self.updateSrc = None
        self.mediaDevice = None

        # *sigh* we still need to be able to write this out
        self.xdriver = None

    def writeXdriver(self, instPath="/"):
        # this should go away at some point, but until it does, we
        # need to keep it around.  it could go into instdata but this
        # isolates it a little more
        if self.xdriver is None:
            return
        if not os.path.isdir("%s/etc/X11" %(instPath,)):
            os.makedirs("%s/etc/X11" %(instPath,), mode=0755)
        f = open("%s/etc/X11/xorg.conf" %(instPath,), 'w')
        f.write('Section "Device"\n\tIdentifier "Videocard0"\n\tDriver "%s"\nEndSection\n' % self.xdriver)
        f.close()

    def setDispatch(self):
        self.dispatch = dispatch.Dispatcher(self)

    def setInstallInterface(self, display_mode):
        # setup links required by graphical mode if installing and verify display mode
        if display_mode == 'g':
            stdoutLog.info (_("Starting graphical installation..."))

            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.")
                display_mode = 't'
                if 'DISPLAY' in os.environ.keys():
                    del os.environ['DISPLAY']
                time.sleep(2)

        if display_mode == 't':
            from text import InstallInterface
            if not os.environ.has_key("LANG"):
                os.environ["LANG"] = "en_US.UTF-8"

        if display_mode == 'c':
            from cmdline import InstallInterface

        self.intf = InstallInterface()

    def setBackend(self, instClass):
        b = instClass.getBackend()
        self.backend = apply(b, (self,))

    def setMethodstr(self, methodstr):
        if methodstr.startswith("cdrom://"):
            (device, tree) = string.split(methodstr[8:], ":", 1)

            if not tree.startswith("/"):
                tree = "/%s" %(tree,)

            self.mediaDevice = device
            self.methodstr = "cdrom://%s" % tree
        else:
            self.methodstr = methodstr

if __name__ == "__main__":
    anaconda = Anaconda()

    setupPythonPath()

    # Allow a file to be loaded as early as possible
    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

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

    import signal, traceback, string, isys, iutil, time
    from exception import handleException
    import dispatch
    import warnings
    import vnc
    import users
    import kickstart
    from flags import flags

    import gettext
    _ = lambda x: gettext.ldgettext("anaconda", x)

    if not iutil.isS390() and os.access("/dev/tty3", os.W_OK):
        logger.addFileHandler ("/dev/tty3", log)

    warnings.showwarning = AnacondaShowWarning

    setupTranslations()

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

    setupEnvironment()

    # 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
    graphical_failed = 0
    instClass = None                # the install class to use
    vncS = vnc.VncServer()          # The vnc Server object.
    xserver_pid = None

    (opts, args) = parseOptions()

    # Now that we've got arguments, do some extra processing.
    instClass = getInstClass()

    setupLoggingFromOpts(opts)

    anaconda.rootPath = opts.rootPath
    # Default is to prompt to mount the installed system.
    anaconda.rescue_mount = not opts.rescue_nomount

    if opts.noipv4:
        flags.useIPv4 = False

    if opts.noipv6:
        flags.useIPv6 = False

    if opts.updateSrc:
        anaconda.updateSrc = opts.updateSrc

    if opts.method:
        if opts.method[0] == '@':
            expandFTPMethod(opts)

        anaconda.setMethodstr(opts.method)
    else:
        anaconda.methodstr = None

    if opts.stage2:
        anaconda.stage2 = opts.stage2

    if opts.liveinst:
        flags.livecdInstall = True

    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
        opts.display_mode = 'g'
        vncS.recoverVNCPassword()

        # Only consider vncconnect when vnc is a param
        if opts.vncconnect:
            cargs = string.split(opts.vncconnect, ":")
            vncS.vncconnecthost = cargs[0]
            if len(cargs) > 1 and len(cargs[1]) > 0:
                if len(cargs[1]) > 0:
                    vncS.vncconnectport = cargs[1]

    if opts.ibft:
        flags.ibft = 1

    if opts.iscsi:
        flags.iscsi = 1

    if opts.targetArch:
        flags.targetarch = opts.targetArch

    # set flags 
    flags.dmraid = opts.dmraid
    flags.mpath = opts.mpath
    flags.selinux = opts.selinux

    if opts.serial:
        flags.serial = True
    if opts.virtpconsole:
        flags.virtpconsole = opts.virtpconsole

    if opts.xdriver:
        anaconda.xdriver = opts.xdriver
        anaconda.writeXdriver()

    # probing for hardware on an s390 seems silly...
    if iutil.isS390():
        opts.isHeadless = True

    if not flags.test and not flags.rootpath:
            isys.auditDaemon()

    users.createLuserConf(anaconda.rootPath)

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

    #
    # must specify install, rescue mode
    #
    if opts.ksfile and (not opts.rescue):
        opts.rescue = setRescueModeFromKickstart(opts)

    if opts.rescue:
        anaconda.rescue = True

        import rescue, instdata

        anaconda.id = instdata.InstallData(anaconda, [], opts.display_mode)

        if opts.ksfile:
            anaconda.isKickstart = True
            instClass.setInstallData(anaconda)
            kickstart.processKickstartFile(anaconda, opts.ksfile)

            # command line 'nomount' overrides kickstart /same for vnc/
            anaconda.rescue_mount = not (opts.rescue_nomount or anaconda.id.ksdata.rescue.nomount)

        rescue.runRescue(anaconda, instClass)

        # shouldn't get back here
        sys.exit(1)

    #
    # Here we have a hook to pull in second half of kickstart file via https
    # if desired.
    #
    if opts.ksfile:
        anaconda.isKickstart = True
        vncksdata = setVNCFromKickstart(opts)

        if vncksdata.enabled:
            opts.display_mode = 'g'

    #
    # Determine install method - GUI or TUI
    #
    # if display_mode wasnt set by command line parameters then set default
    #
    if not opts.display_mode:
        opts.display_mode = 'g'

    if opts.display_mode == 't' and flags.vncquestion: #we prefer vnc over text mode, so ask about that
        title = _("Would you like to use VNC?")
        message = _("The VNC mode installation offers more functionality than the text mode, would you like to use it instead?")

        ret = vnc.askVncWindow(title, message)
        if ret != -1:
            opts.display_mode = 'g'
            flags.usevnc = 1
            if ret is not None:
                vncS.password = ret

    if opts.debug:
        flags.debug = True
        import pdb
        pdb.set_trace()

    import instdata

    import rhpl.keyboard as keyboard

    log.info("anaconda called with cmdline = %s" %(sys.argv,))
    log.info("Display mode = %s" %(opts.display_mode,))

    checkMemory(opts)

    # 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

    #
    # 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 or x_already_set) and (not iutil.isS390() and not os.access("/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:
        try:
            xout = open("/dev/tty5", "w")
            proc = subprocess.Popen(["Xorg", "-br", "-logfile", "/tmp/X.log", ":1", "vt6", "-s", "1440", "-ac", "-nolisten", "tcp"], close_fds=True, stdout=xout, stderr=xout)
            time.sleep(5)
            if proc.poll() is not None:
                raise OSError
            os.environ["DISPLAY"] = ":1"
            doStartupX11Actions(opts.runres)
            xserver_pid = proc.pid
        except OSError:
            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 anaconda.isKickstart:
        ret = vnc.askVncWindow()
        if ret != -1:
            opts.display_mode = 'g'
            flags.usevnc = 1
            if ret is not None:
                vncS.password = ret

    # if they want us to use VNC do that now
    if opts.display_mode == 'g' and flags.usevnc:
        runVNC()
        doStartupX11Actions(opts.runres)

    anaconda.setInstallInterface(opts.display_mode)

    anaconda.setBackend(instClass)

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

    anaconda.id.x_already_set = x_already_set

    anaconda.id.setDisplayMode(opts.display_mode)
    instClass.setInstallData(anaconda)

    anaconda.setDispatch()

    # download and run Dogtail script
    if opts.dogtail:
       try:
           import urlgrabber

           try:
               fr = urlgrabber.urlopen(opts.dogtail)
           except urlgrabber.grabber.URLGrabError, e:
               log.error("Could not retrieve Dogtail script from %s.\nError was\n%s" % (opts.dogtail, e))
               fr = None
                           
           if fr:
               from tempfile import mkstemp

               (fw, testcase) = mkstemp(prefix='testcase.py.', dir='/tmp')
               os.write(fw, fr.read())
               fr.close()
               os.close(fw)
               
               # download completed, run the test
               if not os.fork():
                   # we are in the child
                   os.chmod(testcase, 0755)
                   os.execv(testcase, [testcase])
                   sys.exit(0)
               else:
                   # we are in the parent, sleep to give time for the testcase to initialize
                   # todo: is this needed, how to avoid possible race conditions
                   time.sleep(1)
       except Exception, e:
           log.error("Exception %s while running Dogtail testcase" % e)

    if opts.lang:
        # this is lame, but make things match what we expect (#443408)
        opts.lang = opts.lang.replace(".utf8", ".UTF-8")
        anaconda.dispatch.skipStep("language", permanent = 1)
        anaconda.id.instLanguage.setRuntimeLanguage(opts.lang)
        anaconda.id.instLanguage.setDefault(opts.lang)
        anaconda.id.timezone.setTimezoneInfo(anaconda.id.instLanguage.getDefaultTimeZone())

    if opts.keymap:
        anaconda.dispatch.skipStep("keyboard", permanent = 1)
        anaconda.id.keyboard.set(opts.keymap)
        anaconda.id.keyboard.activate()

    if anaconda.isKickstart:
        kickstart.processKickstartFile(anaconda, opts.ksfile)
        # We need to copy the VNC-related kickstart stuff into the new ksdata
        anaconda.id.ksdata.vnc(enabled=vncksdata.enabled, host=vncksdata.host,
                               password=vncksdata.password, port=vncksdata.port)

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

    if flags.rootpath:
        anaconda.dispatch.skipStep("bootloadersetup", permanent = 1)
        anaconda.dispatch.skipStep("instbootloader", permanent = 1)

    # set up the headless case
    if opts.isHeadless == 1:
        anaconda.id.setHeadless(opts.isHeadless)
        anaconda.dispatch.skipStep("keyboard", permanent = 1)

    if not anaconda.isKickstart:
        instClass.setSteps(anaconda)
    else:
        kickstart.setSteps(anaconda)

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

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

    if anaconda.isKickstart and anaconda.id.ksdata.reboot.eject:
        isys.flushDriveDict()
        for drive in isys.cdromList():
            log.info("attempting to eject %s" % drive)
            isys.ejectCdrom(drive)

    del anaconda.intf
