#!/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 print_color(color,intensity):
    # Add comma to suppress trailing newline
    print "[%d;%dm" % (color,intensity),

def wait_for_answer(signum, frame):
    global partone_timeout

    partone_timeout = 1
    print "Timeout."

def getipinfo():
    while 1:
        iface = raw_input("Interface (ex: eth0): ")
        ip = raw_input("IP Address: ")
        netmask = raw_input("Netmask: ")
        gateway = raw_input("Gateway: ")
        dns = raw_input("DNS Server: ")
        print ""
        print "You entered:"
	print "Iface: %s" % iface
        print "IP: %s" % ip
        print "Netmask: %s" % netmask
        print "Gateway: %s" % gateway
        print "DNS Server: %s" % dns
        print ""
        ok = raw_input("Is this correct? (Y/N) ")
        if ok in ('y', 'Y'): 
             sys.stdout.write("Bringing up network interface...")
             sys.stdout.flush()
             runcmd("ifconfig %s %s netmask %s up" % (iface, ip, netmask))
             runcmd("route add default netmask %s gw %s" % (netmask, gateway))
             resolv = open("/etc/resolv.conf", "w")
             resolv.write("nameserver %s\n" % dns)
             resolv.close()
             netloaded = 1
             globalcfg["interface"] = iface
             print "done."
             return 1
        else:
             print ""


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:
    	#print("line %s" % mtabline)
        mtabfields = string.split(mtabline)
        mtabinfo.append(mtabfields)
        mtabline = mtab.readline()
    mtab.close()


    mtabinfo.reverse()
    for mtabfields in mtabinfo:
        # Trying to umount /proc or /dev causes the installer to fault
        if mtabfields[1] != '/proc' and mtabfields[1] != '/dev':
           #print("umount %s" % mtabfields[1])
           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 error has been encountered that I do not know how to deal with.  Please report
this problem along with all error messages shown above to %s

""" % bug_reports

    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.
"""
    os.system("/bin/sh");
    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
                cmdresult = os.system("modprobe %s" % modpart)
                if cmdresult != 0:
                     print "%s not loaded.  Assuming it is built-in" % modpart
                else:
                     scsiloaded = 1
            elif modpart in netmods:
                print "Loading network module: %s" % modpart
                netloaded = 1
                cmdresult = os.system("modprobe %s" % modpart)
                if cmdresult != 0:
                     print "%s not loaded.  Assuming it is built-in" % modpart
            else:
                print "Module %s detected, but not available - not loading." \
                      % modpart

    # If anything SCSI-related was discovered, load SCSI CD drivers.
    # (and the scsi disk driver, since depmod doesn't seem to realize
    #  that we need it... ? )

    if scsiloaded:
        runcmd("modprobe sr_mod")
        runcmd("modprobe sd_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", "iso9660"]

    # Whether or not to support color output
    color = 1
    red = 31
    normal = 0
    high = 1

    # Specify an email address to include in fatal error messages
    bug_reports = "autoinstall@packages.qa.debian.org"
    scsiloaded = 0
    netloaded = 0
    xserver_found = 0
    partone_timeout = 0
    cmdlinecfg = {}
    globalcfg = {}
    scsimods = []
    netmods = []
    cfgpath = "/etc"
    modulesurl = "http://example.com/scsi_mods.tar"

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


    # 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()
            
    # Debug mode, just drop a shell and give up
    if os.environ.has_key('BOOTTYPE') and os.environ["BOOTTYPE"] == "debug":
        print """
Debug mode selected.  Pushing a shell -- once you exit the system will halt.

Have fun!!
"""
        os.system("/bin/sh")
        killsystem()


    # 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/fd0"
        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 2>/dev/null | 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()

    if not globalcfg.has_key("interface"):
        globalcfg["interface"] = "eth0"

    # 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

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

    if os.environ.has_key('BOOTTYPE') and os.environ["BOOTTYPE"] == "dd":
	print ""
	print "Please insert your Driver Disk in the drive now."
        print "If you do not have a driver disk or wish to skip this step"
        print "please type the word 'none' now."
        ok = raw_input("Hit enter (or 'n' to skip) ")
        if ok in ('n', 'no', 'non', 'none'): 
            pass
        else:
            print "Loading driver disk..."
            os.mkdir("/dd")
            runcmd("mount -t msdos -o ro %s /dd" % (autoinst_config_drive))
            os.system("sh -c 'cd / ; zcat /dd/modules.tgz 2>/dev/null | tar -x -f -'")
            runcmd("umount /dd")
            print "Done with driver disk, you may safely eject it now."
            time.sleep(3)

    # 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 network adapters are setup here.  You can
ignore any warnings about SCSI modules not being available (for the moment).
If the system seems to hang, please reboot and try again.

"""

    detect_hardware()
    if netloaded == 0:
       print """
You do not seem to have a supported network card.  You may wish to try
rebooting and using a supplemental driver disk.  I can't continue without
a network card.
"""
       killsystem()

    # 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 %s" % globalcfg["interface"])[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 %s %s netmask %s broadcast %s" %
                           (globalcfg["interface"],
                            mysettings["ip"], mysettings["netmask"],
                            mysettings["broadcast"]))
                    if mysettings.has_key("gateway"):
                        runcmd("route add default netmask %s gw %s" %
                               (mysettings["gateway"], mysettings["netmask"]))
                    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 %s" % globalcfg["interface"])
            except RuntimeError:
                print "Error configuring the network via DHCP."
                print "If you wish to continue, you may enter your static"
                print "IP information below.  If you do not have a static IP"
                print "your only option is to reboot and try again."
                raw_input("Hit return to enter static IP info > ")
                getipinfo()
            else:
                print "Network configured."
        else:
            raise RuntimeError, "unsupported network configuration type"

    if globalcfg.has_key("modulesurl"):
        print "Trying to load some SCSI modules..."
        runcmd("sh -c 'wget -O /scsi_mods.tar %s'" % globalcfg["modulesurl"])
        runcmd("sh -c 'cd /; tar -x -f scsi_mods.tar'")
        scsiloaded = 0

    netloaded = 1

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

    # 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

    mountlist = []
    freelist = []

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

    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.

        print "Examining drives..."
        try:
           drvinstlist = [parted.get_devices()[0]]
        except:
           if color: print_color(red,high)
           print "No available drives found!"
           if color: print_color(normal,normal)
           print ""
           print "This means that your drive(s) could not be detected."
           print "Please report this as a bug to: %s " % bug_reports
           print ""
           killsystem()

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


        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"):
                        if color: print_color(red,high)
                        print "Error: drive %s already partitioned!" % \
                              drv.get_path()
                        if color: print_color(normal,normal)
                        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"):
                        if color: print_color(red,high)
                        print "\n\n=======> WARNING!!! <======\n\n"
                        print "Drive %s already partitioned!" % drv.get_path()
                        if color: print_color(normal,normal)
                        print """
The drive selected for automatic partitioning has already been
partitioned.  This installation profile is configured to be unsafe.
Thus, partitioning will commence in 30 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(30)
                        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()
            try:
               curpartend = freelist[0][0]
            except:
               if color: print_color(red,high)
               print "No free space available on drive!"
               if color: print_color(normal,normal)
               print """
My configuration file specifies that you want to use only free (unpartitioned) 
space for this install, but I can't seem to find any.  Try deleting the 
partition info for some partitions or try again without the 'freespace' 
configuration option (the install will consume your entire drive in that case).  
Sorry it didn't work out.
"""
               killsystem()

            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

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

                if partfs == "swap":
                    partfs = "linux-swap"
                if partfs == "palo":
                    oldpartfs = partfs
                    partfs = "ext2"
                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)
                if oldpartfs == "palo":
                   palo_fs = partdevice[:-1]
                else:
                   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..."

        # Make sure root is mounted first
        for partinfo in mountlist:
             if partinfo[1] == "/":
                 rootpart = partinfo

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


        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 %s /target%s"
                       % (partdevice, partmount))

    # Done with partitioning and formatting stuff.

    # 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:" or \
               globalcfg["baseurl"][:4] == "ftp:":
                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 2>/dev/null | 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>
""")
    bootdev = ""
    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 partmount == "/boot" or partmount[:6] == "/boot/":
                mntoptions = "defaults,errors=remount-ro"
                bootdev = 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))
    if not bootdev:
        bootdev = rootdev

    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)

    arch = os.popen("chroot /target dpkg --print-architecture 2>/dev/null").read()
    if arch[:4] == "i386":
           required_pkgs.append("grub")
    if arch[:4] == "ia64":
           required_pkgs.append("elilo")
    if arch[:4] == "hppa":
           required_pkgs.append("palo")
           if palo_fs != "":
               print "Toggling palo partition type on %s" % palo_fs
               os.system("chroot /target /bin/sh -c '/bin/echo -e \"t\n1\nf0\np\nw\n\" | /sbin/fdisk %s'" % palo_fs)

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


    if not globalcfg.has_key("disable-minimal"):
        TIMEOUT = 45

        print """
Your system is now configured with a minimum set of packages.  If you wish
you may hit return now -- I will update the installed packages to the latest
versions and then bring up a login prompt. Please note that you will be left 
with an extremely minimal system, and you will almost certainly need to do 
some apt-get'ing to have a useful machine.  This option is meant for expert 
users only.  

Otherwise, in a few seconds I will proceed with installing the packages you 
selected during the system design phase.  If you are unsure, it is recommnded 
that you allow the install to proceed.
"""
        print "Package install will continue in %d seconds..." % TIMEOUT

        signal.signal(signal.SIGALRM, wait_for_answer)
        signal.alarm(TIMEOUT)
        line = sys.stdin.readline()
        signal.alarm(0)

    # End of Part 1

    # Set the package selections.
       
    kver = os.popen("chroot /target uname -r").read()
    kverstring = "kernel-image-%s" % kver

    if partone_timeout == 1 or globalcfg.has_key("disable-minimal"):
       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)
   
               # Set debconf configuration in the environment.
               #os.environ["DEBIAN_FRONTEND"] = "noninteractive"
               #os.environ["DEBIAN_PRIORITY"] = "critical"
               #runcmd("chroot /target /bin/sh -c 'dpkg-preconfigure --priority=critical --frontend=noninteractive /var/cache/apt/archives/debconf_*'")
           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.

    # This is supposed to be an autoinstall, so don't ask any questions
    os.environ["DEBIAN_FRONTEND"] = "noninteractive"
    os.environ["DEBIAN_PRIORITY"] = "critical"

    runcmd("chroot /target /bin/sh -c 'apt-get -yf install dpkg apt'")
    # Force overwriting of any config files
    dpkgconf = open("/target/etc/dpkg/dpkg.cfg", "a")
    dpkgconf.write("force-confnew")
    dpkgconf.close()

    # Make sure required packages are installed.

    print "Updating 'required' packages..."
    print ""

    runcmd("chroot /target /bin/sh -c 'apt-get -yd install debconf'")
    runcmd("chroot /target /bin/sh -c 'dpkg-preconfigure --priority=critical --frontend=noninteractive /var/cache/apt/archives/debconf_*'")
    if arch[:4] == "i386":
        required_pkgs.append("read-edid")
    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.

    print "Creating /dev files"
    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

    if partone_timeout == 1 or globalcfg.has_key("disable-minimal"):
       # Load templates from packages.

       print "Loading configuration data..."

       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)

    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 %s\n\n" % globalcfg["interface"])

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

       ifaces.write("""
#First network card - created by the autoinstaller.
auto %s
""" % globalcfg["interface"])

    if globalcfg["network"] == "netdb":
            ifaces.write("""iface %s inet static
\taddress %s
\tnetmask %s
\tgateway %s
""" % (globalcfg["interface"], 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 %s inet dhcp\n" % globalcfg["interface"])
            nethostname = "debian.autoinstall"
            nethostip = "127.0.0.1"
            runcmd("cp /etc/resolv.conf /target/etc/resolv.conf")
    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()

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

    if partone_timeout == 1 or globalcfg.has_key("disable-minimal"):
       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 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
warn_initrd = NO
""")
       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 '/bin/echo 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")


    # We need a kernel no matter what
    else:
       # 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()
       runcmd("chroot /target /bin/sh -c '/bin/echo yes | apt-get -yf install %s'"
                % kverstring)

    # 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 arch[:4] == "hppa":
        kernel_string = "vmlinux"
    else:
        kernel_string = "vmlinuz"

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

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

    # Install boot loader (whichever one is appropriate).

    for bootfile in os.listdir("/target/boot"):
       if bootfile[:7] == kernel_string:
          kernelpaths.append("boot/%s" % bootfile)
    if len(kernelpaths):
       kernelpaths.sort()
       kernelpaths.reverse()

    nkernel = string.split(kernelpaths[0],"/",1)
    print "Installing boot loader..."
    stanzas = [ { "rootdev": rootdev,
                  "bootdev": bootdev, 
                  "kernel": nkernel[1] } ]
    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

    # Set debconf configuration in the environment.
    os.environ["DEBIAN_FRONTEND"] = "dialog"
    os.environ["DEBIAN_PRIORITY"] = "medium"
    # 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!"

    # Set the dpkg options back to defaults
    dpkgconf = open("/target/etc/dpkg/dpkg.cfg", "w")
    dpkgconf.write("""
# dpkg configuration file
#
# This file can contain default options for dpkg. All commandline
# options are allowed. Values can be specific by putting them after
# the option, seperated by whitespace and/or an `=' sign.
#
no-debsig
""")
    dpkgconf.close()

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

    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.
    os.system("chroot /target /bin/sh -c '/etc/init.d/networking stop'")

    print ""
    if color: print_color(red,high)
    print "NOTICE:"
    if color: print_color(normal,normal)
    print """
Your system is now configured to your specifications.  It is necessary to
reboot to ensure that the correct kernel and modules are loaded.  
Please remove any installation media from your drive(s) now, and power your
machine off and then back on.
"""
    killsystem()

# 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:
