#!/usr/bin/python -i

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

# Arch-specific modules

import partition
import boot

# DebugException class - needed to implement test harness.

class DebugException(Exception):
    pass

# Functions

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

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

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

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

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

    print msg
    while 1:
        time.sleep(3600)

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

    print \
"""EXCEPTION DETECTED!

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

"""

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

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

    killsystem()

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

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

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

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

    return modlist

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

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

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

    return cfglist

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

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

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

    return cfglist

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

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

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

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

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

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

    if scsiloaded:
        runcmd("modprobe sr_mod")

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

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

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

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

def init_debconf_debian():
    global debconf_comm_process

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

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

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

    f.close()

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

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

init_debconf = init_debconf_progeny
set_debconf = set_debconf_progeny
shutdown_debconf = shutdown_debconf_progeny

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

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

try:

    # Initialize some global settings.

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

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

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

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

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

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

    print """
Debian Installation Floppy

Initializing system.
"""

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

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

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

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

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

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

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

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

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

            detect_hardware()

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

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

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

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

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

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

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

    # Globals.

    print "\nLoading global configuration..."

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

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

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

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

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

    # Now set debug flag.

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

    # SCSI module list.

    print "Loading module lists..."

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

    # Network module list.

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

    # Discover hardware and load any necessary devices.

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

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

"""

    detect_hardware()

    # Load network database.

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

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

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

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

        netfile.close()

    # Configure the network.

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

        runcmd("ifconfig lo 127.0.0.1")

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

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

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

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

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

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

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

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

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

"""

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

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

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

    mountlist = []
    freelist = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Unmount the CD if it's mounted.

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

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

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

    # Load partition information from the floppy, if necessary.

        print "Reading partition configuration..."

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

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

    # Find all drives.

        print "Searching for drives..."

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

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

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

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

        print "Examining drives..."

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

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

                drvdisk.close()

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

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

    # Partition and format drive.

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

            drvobj = partition.Partition(drv)

            drvsectors = drv.get_length()

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

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

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

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

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

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

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

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

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

            drvobj.commit_changes()

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

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

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

            drvdisk.close()
            drv.close()

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

        parted.done()

    # Mount drives.

        print "Mounting drives..."

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

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

    # Remount the CD in the right place.

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

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

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

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

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

"""
            killsystem()

    # Untar the base system from the archive.

        print "Extracting base system..."

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

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

    # Mount a second /proc for chrooted utilities.

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

    # Write /etc/fstab.

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

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

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

    fstab.close()

    # Set the root password.

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

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

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

    oldpwd.close()
    newpwd.close()

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

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

    print "Configuring package system..."

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

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

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

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

    # Set the package selections.

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

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

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

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

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

        selectionsfile.close()
        dpkgpipe.close()

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

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

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

    # Pre-download packages to allow debconf seeding.

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

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

    # Update dpkg and apt to the latest versions.

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

    # Make sure required packages are installed.

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

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

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

    # Load templates from packages.

    print "Loading configuration data..."

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

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

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

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

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

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

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

    init_debconf()

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

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

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

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

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

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

        etherconfcfg.close()

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

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

            # Straight Debian - no etherconf.

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

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

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

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

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

                nethostip = mysettings["ip"]

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

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

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

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

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

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

        ifaces.close()

    # Update discover to prepare for X installation.

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

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

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

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

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

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

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

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

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

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

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

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

        xconf.close()

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

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

    # Set special kernel configuration to prevent kernel postinst message.

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

    # We're done playing with debconf now.

    shutdown_debconf()

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

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

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

    print "Installing packages..."

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

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

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

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

    print "\nDone with packages."

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

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

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

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

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

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

    # Install boot loader (whichever one is appropriate).

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

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

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

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

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

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

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

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

"""

    # Set the root partition to use when we exit.

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

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

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

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

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

    # Make sure the base tarball is gone.

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

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

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

    # Kill pump off if we're using DHCP.

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

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

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

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

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

    # Unmount all mounted partitions.

    unmountall()

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

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

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

sys.exit(0)

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

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

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

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

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