#!/usr/bin/python -tt
#
# Script to set up a Xen guest and kick off an install
#
# Copyright 2005-2006  Red Hat, Inc.
# Jeremy Katz <katzj@redhat.com>
# Option handling added by Andrew Puch <apuch@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.

import os, sys
import time
import errno
import re
import logging
import optparse
from optparse import OptionGroup

import urlgrabber.progress as progress

import libvirt
import virtinst
import virtinst.CapabilitiesParser
import virtinst.cli as cli
from virtinst.VirtualCharDevice import VirtualCharDevice
from virtinst.VirtualDevice import VirtualDevice
from virtinst.cli import fail

cli.setupGettext()

DEFAULT_POOL_PATH = "/var/lib/libvirt/images"
DEFAULT_POOL_NAME = "default"

def partition(string, sep):
    if not string:
        return (None, None, None)

    if string.count(sep):
        splitres = string.split(sep, 1)
        ret = (splitres[0], sep, splitres[1])
    else:
        ret = (string, None, None)
    return ret

def build_default_pool(guest):

    if not virtinst.util.is_storage_capable(guest.conn):
        # VirtualDisk will raise an error for us
        return
    pool = None
    try:
        pool = guest.conn.storagePoolLookupByName(DEFAULT_POOL_NAME)
    except libvirt.libvirtError:
        pass

    if pool:
        return

    try:
        logging.debug("Attempting to build default pool with target '%s'" %
                      DEFAULT_POOL_PATH)
        defpool = virtinst.Storage.DirectoryPool(conn=guest.conn,
                                                 name=DEFAULT_POOL_NAME,
                                                 target_path=DEFAULT_POOL_PATH)
        newpool = defpool.install(build=True, create=True)
        newpool.setAutostart(True)
    except Exception, e:
        raise RuntimeError(_("Couldn't create default storage pool '%s': %s") %
                             (DEFAULT_POOL_PATH, str(e)))

def parse_char_option(guest, char_type, optstring):
    """
    Helper to parse --serial/--parallel options
    """
    # Peel the char type off the front
    dev_type, ignore, optstring = partition(optstring, ",")

    opts = cli.parse_optstr(optstring)

    dev = VirtualCharDevice.get_dev_instance(guest.conn, char_type, dev_type)

    def set_param(paramname, dictname, val=None):
        if not val:
            if opts.has_key(dictname):
                val = opts[dictname]
                del(opts[dictname])
            else:
                return

        if not hasattr(dev, paramname):
            raise ValueError(_("%(chartype)s type %(devtype)s does not "
                                "support '%(optname)s' option.") %
                                {"chartype" : char_type, "devtype": dev_type,
                                 "optname" : dictname} )
        setattr(dev, paramname, val)

    def parse_host(key):
        host, ignore, port = partition(opts.get(key), ":")
        if opts.has_key(key):
            del(opts[key])

        return host, port

    host, port = parse_host("host")
    bind_host, bind_port = parse_host("bind_host")

    set_param("source_path", "path")
    set_param("source_mode", "mode")
    set_param("protocol",   "protocol")
    set_param("source_host", "host", host)
    set_param("source_port", "host", port)
    set_param("bind_host", "bind_host", bind_host)
    set_param("bind_port", "bind_host", bind_port)

    # If extra parameters, then user passed some garbage param
    if opts:
        raise ValueError(_("Unknown option(s) %s") % opts.keys())

    # Try to generate dev XML to perform upfront validation
    dev.get_xml_config()

    return dev

def get_chardevs(char_type, opts, guest):

    for optstr in cli.listify(opts):
        try:
            dev = parse_char_option(guest, char_type, optstr)
            guest.add_device(dev)
        except Exception, e:
            fail(_("Error in %(chartype)s device parameters: %(err)s") %
                 {"chartype": char_type, "err": str(e) })

def parse_watchdog(guest, optstring):
    # Peel the model type off the front
    model, ignore, optstring = partition(optstring, ",")
    opts = cli.parse_optstr(optstring)
    dev = virtinst.VirtualWatchdog(guest.conn)

    def set_param(paramname, dictname, val=None):
        if not val:
            if opts.has_key(dictname):
                val = opts[dictname]
                del(opts[dictname])
            else:
                return

        setattr(dev, paramname, val)

    set_param("model", "model", model)
    set_param("action", "action")

    # If extra parameters, then user passed some garbage param
    if opts:
        raise ValueError(_("Unknown option(s) %s") % opts.keys())

    return dev

def get_watchdog(watchdogs, guest):
    for optstr in cli.listify(watchdogs):
        try:
            dev = parse_watchdog(guest, optstr)
            guest.add_device(dev)
        except Exception, e:
            fail(_("Error in watchdog device parameters: %s") % str(e))

def get_security(security, guest):
    seclist = cli.listify(security)
    secopts = seclist and seclist[0] or None
    if not secopts:
        return

    # Parse security opts
    opts = cli.parse_optstr(secopts)
    secmodel = virtinst.Seclabel(guest.conn)

    def get_and_clear(dictname):
        val = None
        if opts.has_key(dictname):
            val = opts[dictname]
            del(opts[dictname])
        return val

    mode = get_and_clear("type")
    label = get_and_clear("label")

    if label:
        secmodel.label = label
        if not mode:
            mode = secmodel.SECLABEL_TYPE_STATIC
    if mode:
        secmodel.type = mode

    # If extra parameters, then user passed some garbage param
    if opts:
        raise ValueError(_("Unknown option(s) %s") % opts.keys())

    secmodel.get_xml_config()
    guest.seclabel = secmodel

def parse_disk_option(guest, path, size):
    """helper to properly parse --disk options"""
    abspath = None
    voltuple = None
    volinst = None
    ro = False
    shared = False
    sparse = True
    option_whitelist = ["perms", "cache", "bus", "device", "size", "sparse",
                        "format"]

    # Strip media type
    path, ignore, optstr = partition(path, ",")
    path_type = None
    if path.startswith("path="):
        path_type = "path="
    elif path.startswith("vol="):
        path_type = "vol="
    elif path.startswith("pool="):
        path_type = "pool="

    if path_type:
        path = path[len(path_type):]
    else:
        # Allow a default fallback mode --disk /some/path,foo,rah
        path_type = "path="

    # Parse out comma separated options
    opts = cli.parse_optstr(optstr)
    for opt_type, opt_val in opts.items():
        if opt_type not in option_whitelist:
            fail(_("Unknown --disk option '%s'.") % opt_type)

        if opt_type == "perms":
            if opt_val == "ro":
                ro = True
            elif opt_val == "sh":
                shared = True
            else:
                fail(_("Unknown '%s' value '%s'" % (opt_type, opt_val)))
        elif opt_type == "size":
            try:
                size = float(opt_val)
            except Exception, e:
                fail(_("Improper value for 'size': %s" % str(e)))
        elif opt_type == "sparse":
            if opt_val == "true":
                sparse = True
            elif opt_val == "false":
                sparse = False
            else:
                fail(_("Unknown '%s' value '%s'") % (opt_type, opt_val))

    # Set simple options from dictionary
    devtype = opts.get("device")
    bus     = opts.get("bus")
    cache   = opts.get("cache")
    fmt     = opts.get("format")

    # We return (path, (poolname, volname), volinst, device, bus, readonly,
    #            shared)
    if path_type == "path=":
        abspath = os.path.abspath(path)
        if os.path.dirname(abspath) == DEFAULT_POOL_PATH:
            build_default_pool(guest)

    elif path_type == "pool=":
        if not size:
            raise ValueError(_("Size must be specified with all 'pool='"))
        if path == DEFAULT_POOL_NAME:
            build_default_pool(guest)
        vc = virtinst.Storage.StorageVolume.get_volume_for_pool(pool_name=path,
                                                                conn=guest.conn)
        vname = virtinst.Storage.StorageVolume.find_free_name(conn=guest.conn,
                                                              pool_name=path,
                                                              name=guest.name,
                                                              suffix=".img")
        volinst = vc(pool_name=path, name=vname, conn=guest.conn,
                     allocation=0, capacity=(size and size*1024*1024*1024))
        if fmt:
            if not hasattr(volinst, "format"):
                raise ValueError(_("Format attribute not supported for this "
                                   "volume type"))
            setattr(volinst, "format", fmt)

        if not sparse:
            volinst.allocation = volinst.capacity

    elif path_type == "vol=":
        if not path.count("/"):
            raise ValueError(_("Storage volume must be specified as "
                               "vol=poolname/volname"))
        vollist = path.split("/")
        voltuple = (vollist[0], vollist[1])
        logging.debug("Parsed volume: as pool='%s' vol='%s'" % \
                      (voltuple[0], voltuple[1]))
        if voltuple[0] == DEFAULT_POOL_NAME:
            build_default_pool(guest)

    if not devtype:
        devtype = virtinst.VirtualDisk.DEVICE_DISK

    # Mapping to VirtualDisk __init__ options
    kwargs = { 'conn' : guest.conn,
               'path': path,
               'size': size,
               'sparse': sparse,
               'volInstall': volinst,
               'volName': voltuple,
               'readOnly': ro,
               'shareable': shared,
               'device': devtype,
               'bus': bus,
               'driverCache': cache,
               'format': fmt }

    logging.debug("parse_disk: returning %s" % str(kwargs))
    return kwargs

def get_disk(disk, size, sparse, guest, conn, is_file_path):

    try:
        if is_file_path:
            kwargs = { 'conn': conn, 'path': disk, 'size': size,
                       'sparse': sparse,
                       'device': virtinst.VirtualDisk.DEVICE_DISK }
        else:
            kwargs = parse_disk_option(guest, disk, size)

        d = cli.disk_prompt(None, kwargs)

    except ValueError, e:
        fail(_("Error with storage parameters: %s" % str(e)))

    guest.disks.append(d)

def get_disks(file_paths, disk_paths, size, sparse, nodisks, guest, conn):
    if nodisks:
        if file_paths or disk_paths or size:
            fail(_("Cannot use --file, --file-size, or --disk with --nodisks"))
        return
    if (file_paths or size or sparse == False) and disk_paths:
        fail(_("Cannot mix --file, --nonsparse, or --file-size with --disk "
               "options. Please see the manual for --disk syntax."))
    elif not file_paths and not disk_paths and not cli.is_prompt():
        fail(_("A disk must be specified (use --nodisks to override)"))

    is_file_path = (file_paths or (not disk_paths and cli.is_prompt()))
    disk = (file_paths or disk_paths)

    # ensure we have equal length lists
    if (type(disk) == type(size) == list):
        if len(disk) != len(size):
            fail(_("Need to pass size for each disk"))
    elif type(disk) == list:
        size = [ None ] * len(disk)
    elif type(size) == list:
        disk = [ None ] * len(size)

    if type(disk) == list or type(size) == list:
        map(lambda d, s: get_disk(d, s, sparse, guest, conn,
                                  is_file_path), disk, size)
    else:
        get_disk(disk, size, sparse, guest, conn, is_file_path)

def get_networks(macs, bridges, networks, nonetworks, guest):
    if nonetworks:
        if macs:
            fail(_("Cannot use --mac with --nonetworks"))
        if bridges:
            fail(_("Cannot use --bridges with --nonetworks"))
        if networks:
            fail(_("Cannot use --network with --nonetworks"))
        return
    net_kwargs = cli.digest_networks(guest.conn, macs, bridges, networks,
                                     nics=1)
    map(lambda kwargs: cli.get_network(kwargs, guest), net_kwargs)

def prompt_virt(caps, arch, req_virt_type, req_accel):

    supports_hvm   = False
    supports_pv    = False
    supports_accel = False
    for guest in caps.guests:
        if guest.os_type == "hvm":
            supports_hvm = True

        elif guest.os_type == "xen":
            if (len(guest.domains) and
                guest.domains[0].hypervisor_type == "kvm"):
                # Don't prompt user for PV w/ xenner
                continue
            supports_pv = True

    if not arch:
        arch = caps.host.arch

    if not req_virt_type:
        if supports_hvm and supports_pv:
            prompt_txt = _("Would you like a fully virtualized guest "
                           "(yes or no)? This will allow you to run "
                           "unmodified operating systems.")

            if cli.prompt_for_yes_or_no(prompt_txt, ""):
                req_virt_type = "hvm"
            else:
                req_virt_type = "xen"

        elif supports_hvm:
            req_virt_type = "hvm"

        elif supports_pv:
            req_virt_type = "xen"

    # See if that domain supports acceleration
    accel_type = ""
    for guest in caps.guests:
        if guest.os_type == req_virt_type and guest.arch == arch:
            for dom in guest.domains:
                if dom.hypervisor_type in [ "kvm", "kqemu" ]:
                    supports_accel = True
                    accel_type = dom.hypervisor_type.upper()

    if supports_accel and not req_accel:
        prompt_txt = (_("Would you like to use %s acceleration? "
                        "(yes or no)") % accel_type)

        req_accel = cli.prompt_for_yes_or_no(prompt_txt, "")

    return (req_virt_type, req_accel)


def get_virt_type(conn, options):

    # Set up all virt/hypervisor parameters
    if options.fullvirt and options.paravirt:
        fail(_("Can't do both --hvm and --paravirt"))

    capabilities = virtinst.CapabilitiesParser.parse(conn.getCapabilities())

    # Accelerate request is now the default
    req_accel = True
    req_hv_type = options.hv_type and options.hv_type.lower() or None
    if options.fullvirt:
        req_virt_type = "hvm"
    elif options.paravirt:
        req_virt_type = "xen"
    else:
        # This should force capabilities to give us the most sensible default
        req_virt_type = None

    if cli.is_prompt():
        # User requested prompting but passed no virt type flag, ask for
        # needed info
        req_virt_type, req_accel = prompt_virt(capabilities, options.arch,
                                               req_virt_type, req_accel)

    logging.debug("Requesting virt method '%s', hv type '%s'." %
                  ((req_virt_type and req_virt_type or _("default")),
                   (req_hv_type and req_hv_type or _("default"))))

    arch = options.arch
    if re.match("i.86", arch or ""):
        arch = "i686"

    try:
        (capsguest,
         capsdomain) = virtinst.CapabilitiesParser.guest_lookup(conn=conn,
                        caps=capabilities, os_type=req_virt_type,
                        arch=arch, type=req_hv_type, accelerated=req_accel)
    except Exception, e:
        fail(e)

    return (capsguest, capsdomain)


def get_install_media(location, cdpath, pxe, livecd, import_install,
                      guest, ishvm):

    found = False
    for m in [pxe, location, cdpath, import_install]:
        if m:
            if found:
                fail(_("Only one install method (%s) can be used") %
                       "--pxe, --location, --cdrom, --import")
            found = True

    if not ishvm:
        if pxe:
            fail(_("Network PXE boot is not supported for paravirtualized "
                   "guests"))
        if cdpath or livecd:
            fail(_("Paravirtualized guests cannot install off cdrom media."))

    if location and virtinst.util.is_uri_remote(guest.conn.getURI()):
        fail(_("--location can not be specified for remote connections."))

    cdinstall = (cdpath or False)
    if not (pxe or cdpath or location or import_install):
        # Look at Guest disks: if there is a cdrom, use for install
        for disk in guest.disks:
            if disk.device == virtinst.VirtualDisk.DEVICE_CDROM:
                cdinstall = True
        if not cdinstall and not cli.is_prompt():
            fail(_("One of %s, or cdrom media must be specified.") %
                  "--pxe, --location, --import")


    if pxe or import_install:
        return

    try:
        if not location and not cdpath and cli.is_prompt():
            media_prompt(guest, ishvm)
        else:
            validate_install_media(guest, location, cdpath, cdinstall)
    except ValueError, e:
        fail(_("Error creating cdrom disk: %s" % str(e)))

def media_prompt(guest, ishvm):

    if ishvm:
        prompt_txt = _("What is the install CD-ROM/ISO or URL?")
    else:
        prompt_txt = _("What is the install URL?")

    while 1:
        location = None
        cdpath = None
        media = cli.prompt_for_input("", prompt_txt, None)

        if not ishvm or media.count(":/"):
            location = media
        else:
            cdpath = media

        try:
            validate_install_media(guest, location, cdpath)
        except Exception, e:
            logging.error(str(e))
            continue
        break

def validate_install_media(guest, location, cdpath, cdinstall=False):
    if location or cdpath:
        guest.location = (location or cdpath)

    if cdinstall or cdpath:
        guest.installer.cdrom = True


### Option parsing
def parse_args():
    usage = "%prog --name NAME --ram RAM STORAGE INSTALL [options]"
    parser = cli.setupParser(usage)

    parser.add_option("", "--connect", type="string", dest="connect",
                      action="callback", callback=cli.check_before_store,
                      help=_("Connect to hypervisor with URI"),
                      default=None)

    geng = OptionGroup(parser, _("General Options"))
    geng.add_option("-n", "--name", type="string", dest="name",
                    action="callback", callback=cli.check_before_store,
                    help=_("Name of the guest instance"))
    geng.add_option("-r", "--ram", type="int", dest="memory",
                    help=_("Memory to allocate for guest instance in "
                           "megabytes"))
    geng.add_option("", "--vcpus", type="int", dest="vcpus",
                    help=_("Number of vcpus to configure for your guest"))
    geng.add_option("", "--cpuset", type="string", dest="cpuset",
                    action="callback", callback=cli.check_before_store,
                    help=_("Set which physical CPUs Domain can use."))
    geng.add_option("", "--description", type="string", dest="description",
                    action="callback", callback=cli.check_before_store,
                    help=_("Human readable description of the VM to store in "
                           "the generated XML."))
    geng.add_option("", "--security", type="string", dest="security",
                    action="callback", callback=cli.check_before_store,
                    help=_("Set domain security driver configuration."))
    parser.add_option_group(geng)

    insg = OptionGroup(parser, _("Installation Method Options"))
    insg.add_option("-c", "--cdrom", type="string", dest="cdrom",
                    action="callback", callback=cli.check_before_store,
                    help=_("CD-ROM installation media"))
    insg.add_option("-l", "--location", type="string", dest="location",
                    action="callback", callback=cli.check_before_store,
                    help=_("Installation source (eg, nfs:host:/path, "
                           "http://host/path, ftp://host/path)"))
    insg.add_option("", "--pxe", action="store_true", dest="pxe",
                    help=_("Boot from the network using the PXE protocol"))
    insg.add_option("", "--import", action="store_true", dest="import_install",
                    help=_("Build guest around an existing disk image"))
    insg.add_option("", "--livecd", action="store_true", dest="livecd",
                    help=_("Treat the CD-ROM media as a Live CD"))
    insg.add_option("-x", "--extra-args", type="string", dest="extra",
                    default="",
                    help=_("Additional arguments to pass to the kernel "
                           "booted from --location"))
    insg.add_option("", "--os-type", type="string", dest="distro_type",
                    action="callback", callback=cli.check_before_store,
                    help=_("The OS type being installed, e.g. "
                           "'linux', 'unix', 'windows'"))
    insg.add_option("", "--os-variant", type="string", dest="distro_variant",
                      action="callback", callback=cli.check_before_store,
                      help=_("The OS variant being installed guests, "
                             "e.g. 'fedora6', 'rhel5', 'solaris10', 'win2k'"))
    parser.add_option_group(insg)

    stog = OptionGroup(parser, _("Storage Configuration"))
    stog.add_option("", "--disk", type="string", dest="diskopts",
                    action="callback", callback=cli.check_before_append,
        help=_("Specify storage with various options. Ex.\n"
               "--disk path=/my/existing/disk\n"
               "--disk path=/my/new/disk,size=5 (in gigabytes)\n"
               "--disk vol=poolname:volname,device=cdrom,bus=scsi,..."))
    stog.add_option("", "--nodisks", action="store_true",
                    help=_("Don't set up any disks for the guest."))

    # Deprecated storage options
    stog.add_option("-f", "--file", type="string", dest="file_path",
                    action="callback", callback=cli.check_before_append,
                    help=optparse.SUPPRESS_HELP)
    stog.add_option("-s", "--file-size", type="float",
                    action="append", dest="disksize",
                    help=optparse.SUPPRESS_HELP)
    stog.add_option("", "--nonsparse", action="store_false",
                    default=True, dest="sparse",
                    help=optparse.SUPPRESS_HELP)
    parser.add_option_group(stog)

    netg = OptionGroup(parser, _("Networking Configuration"))
    netg.add_option("-w", "--network", type="string", dest="network",
                    action="callback", callback=cli.check_before_append,
      help=_("Specify a network interface. Ex:\n"
             "--network bridge=mybr0\n"
             "--network network=my_libvirt_virtual_net\n"
             "--network network=mynet,model=virtio,mac=00:11..."))
    netg.add_option("", "--nonetworks", action="store_true",
                    help=_("Don't create network interfaces for the guest."))

    # Deprecated net options
    netg.add_option("-b", "--bridge", type="string", dest="bridge",
                    action="callback", callback=cli.check_before_append,
                    help=optparse.SUPPRESS_HELP)
    netg.add_option("-m", "--mac", type="string", dest="mac",
                    action="callback", callback=cli.check_before_append,
                    help=optparse.SUPPRESS_HELP)
    parser.add_option_group(netg)

    vncg = cli.graphics_option_group(parser)
    vncg.add_option("", "--noautoconsole", action="store_false",
                    dest="autoconsole",
                    help=_("Don't automatically try to connect to the guest "
                           "console"))
    parser.add_option_group(vncg)

    devg = OptionGroup(parser, _("Device Options"))
    devg.add_option("", "--serial", type="string", dest="serials",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a serial device to the domain."))
    devg.add_option("", "--parallel", type="string", dest="parallels",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a parallel device to the domain."))
    devg.add_option("", "--host-device", type="string", dest="hostdevs",
                    action="callback", callback=cli.check_before_append,
                    help=_("Physical host device to attach to the domain."))
    devg.add_option("", "--soundhw", type='string', action="callback",
                    callback=cli.check_before_append, dest="soundhw",
                    help=_("Use sound device emulation"))
    devg.add_option("", "--watchdog", type="string", dest="watchdog",
                    action="callback", callback=cli.check_before_append,
                    help=_("Add a watchdog device to the domain."))
    devg.add_option("", "--video", dest="video", type="string",
                    action="callback", callback=cli.check_before_append,
                    help=_("Specify video hardware type."))

    # Deprecated
    devg.add_option("", "--sound", action="store_true", dest="sound",
                    default=False, help=optparse.SUPPRESS_HELP)
    parser.add_option_group(devg)

    virg = OptionGroup(parser, _("Virtualization Platform Options"))
    virg.add_option("-v", "--hvm", action="store_true", dest="fullvirt",
                      help=_("This guest should be a fully virtualized guest"))
    virg.add_option("-p", "--paravirt", action="store_true", dest="paravirt",
                    help=_("This guest should be a paravirtualized guest"))
    virg.add_option("", "--virt-type", type="string", dest="hv_type",
                    default="",
                    help=_("Hypervisor name to use (kvm, qemu, xen, ...)"))
    virg.add_option("", "--accelerate", action="store_true",
                    dest="accelerate", default=False,
                    help=optparse.SUPPRESS_HELP)
    virg.add_option("", "--arch", type="string", dest="arch",
                    action="callback", callback=cli.check_before_store,
                    help=_("The CPU architecture to simulate"))
    virg.add_option("", "--noapic", action="store_true", dest="noapic",
                    default=False,
                    help=_("Disables APIC for fully virtualized guest "
                           "(overrides value in os-type/os-variant db)"))
    virg.add_option("", "--noacpi", action="store_true", dest="noacpi",
                    default=False,
                    help=_("Disables ACPI for fully virtualized guest "
                           "(overrides value in os-type/os-variant db)"))
    virg.add_option("-u", "--uuid", type="string", dest="uuid",
                    action="callback", callback=cli.check_before_store,
                    help=_("UUID for the guest."))
    parser.add_option_group(virg)

    misc = OptionGroup(parser, _("Miscellaneous Options"))
    misc.add_option("", "--autostart", action="store_true", default=False,
                    dest="autostart",
                    help=_("Have domain autostart on host boot up."))
    misc.add_option("", "--noreboot", action="store_true", dest="noreboot",
                    help=_("Disables the automatic rebooting when the "
                           "installation is complete."))
    misc.add_option("", "--wait", type="int", dest="wait",
                    help=_("Time to wait (in minutes)"))
    misc.add_option("", "--force", action="store_true", dest="force",
                    help=_("Forces 'yes' for any applicable prompts, "
                           "terminates for all others"),
                      default=False)
    misc.add_option("", "--prompt", action="store_true", dest="prompt",
                    help=_("Request user input for ambiguous situations or "
                           "required options."), default=False)
    misc.add_option("", "--check-cpu", action="store_true", dest="check_cpu",
                    help=_("Check that vcpus do not exceed physical CPUs "
                             "and warn if they do."))
    misc.add_option("-d", "--debug", action="store_true", dest="debug",
                    help=_("Print debugging information"))
    parser.add_option_group(misc)

    (options, dummy) = parser.parse_args()
    return options


def vnc_console(dom, uri):
    args = ["/usr/bin/virt-viewer"]
    if uri is not None and uri != "":
        args = args + [ "--connect", uri]
    args = args + [ "--wait", "%s" % dom.ID()]
    child = os.fork()
    if not child:
        try:
            os.execvp(args[0], args)
        except OSError, (err, msg):
            if err == errno.ENOENT:
                print _("Unable to connect to graphical console: virt-viewer not installed. Please install the 'virt-viewer' package.")
            else:
                raise OSError, (err, msg)
        os._exit(1)

    return child

def txt_console(dom, uri):
    args = ["/usr/bin/virsh"]
    if uri is not None and uri != "":
        args = args + [ "--connect", uri]
    args = args + [ "console", "%s" % dom.ID()]
    child = os.fork()
    if not child:
        os.execvp(args[0], args)
        os._exit(1)

    return child

### Let's do it!
def main():
    options = parse_args()

    # Default setup options
    cli.setupLogging("virt-install", options.debug)
    cli.set_force(options.force)
    cli.set_prompt(options.prompt)
    conn = cli.getConnection(options.connect)

    capsguest, capsdomain = get_virt_type(conn, options)

    virt_type = capsguest.os_type
    hv_name = capsdomain.hypervisor_type
    logging.debug("Received virt method '%s'" % virt_type)
    logging.debug("Hypervisor name is '%s'" % hv_name)


    # Build the Installer instance
    if options.livecd:
        instclass = virtinst.LiveCDInstaller
    elif options.pxe:
        if options.nonetworks:
            fail(_("Can't use --pxe with --nonetworks"))

        instclass = virtinst.PXEInstaller
    elif options.import_install:
        instclass = virtinst.ImportInstaller
    else:
        instclass = virtinst.DistroInstaller
    installer = instclass(type=hv_name, os_type=virt_type, conn=conn)
    installer.arch = capsguest.arch


    # Get Guest instance from installer parameters.
    guest = installer.guest_from_installer()


    # now let's get some of the common questions out of the way
    if virt_type == "hvm":
        ishvm = True
    else:
        ishvm = False

    cli.get_name(options.name, guest)
    cli.get_memory(options.memory, guest)
    cli.get_uuid(options.uuid, guest)
    cli.get_vcpus(options.vcpus, options.check_cpu, guest, conn)
    cli.get_cpuset(options.cpuset, guest.memory, guest, conn)
    get_security(options.security, guest)

    get_watchdog(options.watchdog, guest)
    cli.get_sound(options.sound, options.soundhw, guest)
    get_chardevs(VirtualDevice.VIRTUAL_DEV_SERIAL, options.serials, guest)
    get_chardevs(VirtualDevice.VIRTUAL_DEV_PARALLEL, options.parallels, guest)

    guest.autostart = options.autostart
    guest.description = options.description

    # set up disks
    get_disks(options.file_path, options.diskopts, options.disksize,
              options.sparse, options.nodisks, guest, conn)

    # set up network information
    get_networks(options.mac, options.bridge, options.network,
                 options.nonetworks, guest)

    # set up graphics and video device information
    cli.get_graphics(options.vnc, options.vncport, options.vnclisten,
                     options.nographics, options.sdl, options.keymap,
                     options.video, guest)

    # Set host device info
    cli.get_hostdevs(options.hostdevs, guest)

    guest.extraargs = options.extra
    cli.set_os_variant(guest, options.distro_type, options.distro_variant)

    # and now for the full-virt vs paravirt specific questions
    get_install_media(options.location, options.cdrom, options.pxe,
                      options.livecd, options.import_install, guest, ishvm)

    continue_inst = guest.get_continue_inst()
    if options.noacpi:
        guest.features["acpi"] = False
    if options.noapic:
        guest.features["apic"] = False

    def show_console(dom):
        if guest.graphics_dev:
            if guest.graphics_dev.type == virtinst.VirtualGraphics.TYPE_VNC:
                return vnc_console(dom, options.connect)
            else:
                return None # SDL needs no viewer app
        else:
            return txt_console(dom, options.connect)

    # There are two main cases we care about:
    #
    # Scripts: these should specify --wait always, maintaining the
    # semantics of virt-install exit implying the domain has finished
    # installing.
    #
    # Interactive: If this is a continue_inst domain, we default to
    # waiting.  Otherwise, we can exit before the domain has finished
    # installing. Passing --wait will give the above semantics.
    #
    wait = continue_inst
    wait_time = -1
    autoconsole = options.autoconsole

    if options.wait != None:
        wait = True
        wait_time = options.wait * 60
        if wait_time == 0:
            # --wait 0 implies --noautoconsole
            autoconsole = False

    if autoconsole is False:
        conscb = None
    else:
        conscb = show_console

    progresscb = progress.TextMeter()


    # we've got everything -- try to start the install
    print _("\n\nStarting install...")

    try:
        start_time = time.time()

        # Do first install phase
        dom = do_install(guest, conscb, progresscb, wait, wait_time,
                         start_time, guest.start_install)

        # This should be valid even before doing continue install
        if not guest.post_install_check():
            print _("Domain installation does not appear to have been\n "
                    "successful.  If it was, you can restart your domain\n "
                    "by running 'virsh start %s'; otherwise, please\n "
                    "restart your installation.") % guest.name
            sys.exit(0)

        if continue_inst:
            dom = do_install(guest, conscb, progresscb, wait, wait_time,
                             start_time, guest.continue_install)

        if options.noreboot:
            print _("Guest installation complete... you can restart your "
                    "domain\nby running 'virsh start %s'") % guest.name
        else:
            # FIXME: Should we say 'installation' complete for livecd, import?
            print _("Guest installation complete... restarting guest.")
            dom.create()
            guest.connect_console(conscb)

    except KeyboardInterrupt, e:
        guest.terminate_console()
        print _("Guest install interrupted.")
    except RuntimeError, e:
        fail(e)
    except SystemExit, e:
        sys.exit(e.code)
    except Exception, e:
        logging.error(e)
        print _("Domain installation does not appear to have been\n "
                "successful.  If it was, you can restart your domain\n "
                "by running 'virsh start %s'; otherwise, please\n "
                "restart your installation.") % guest.name
        raise


def do_install(guest, conscb, progresscb, wait, wait_time, start_time,
               install_func):

    dom = install_func(conscb, progresscb, wait=(not wait))

    # Wait a bit so info is accurate
    def check_domain_state():
        dominfo = dom.info()
        state = dominfo[0]

        if guest.domain_is_crashed():
            print _("Domain has crashed.")
            sys.exit(1)

        if guest.domain_is_shutdown():
            return dom, state

        return None, state

    do_sleep = bool(conscb)
    try:
        ret, state = check_domain_state()
        if ret:
            return ret
    except Exception, e:
        # Sometimes we see errors from libvirt here due to races
        logging.exception(e)
        do_sleep = True

    if do_sleep:
        # Sleep a bit and try again to be sure the HV has caught up
        time.sleep(2)

    ret, state = check_domain_state()
    if ret:
        return ret

    logging.debug("Domain state after install: %s" % state)

    # Domain seems to be running
    if wait and wait_time != 0:
        timestr = ""
        if wait_time > 0:
            timestr = _("%d minutes ") % (int(wait_time) / 60)

        print _("Domain installation still in progress. Waiting %s"
                "for installation to complete.") % timestr

        # Wait loop
        while True:
            if guest.domain_is_shutdown():
                print _("Domain has shutdown. Continuing.")
                try:
                    # Lookup a new domain object incase current
                    # one returned bogus data (see comment in
                    # domain_is_shutdown
                    dom = guest.conn.lookupByName(guest.name)
                except Exception, e:
                    raise RuntimeError(_("Could not lookup domain after "
                                         "install: %s" % str(e)))
                break

            if wait_time < 0 or ((time.time() - start_time) < wait_time):
                time.sleep(2)
            else:
                print _("Installation has exceeded specified time limit. "
                        "Exiting application.")
                sys.exit(1)
    else:
        # User specified --wait 0, which means --noautoconsole, which
        # means just exit.
        print _("Domain installation still in progress. You can reconnect"
                " to \nthe console to complete the installation process.")
        sys.exit(0)

    return dom

if __name__ == "__main__":
    try:
        main()
    except SystemExit, sys_e:
        sys.exit(sys_e.code)
    except KeyboardInterrupt:
        print >> sys.stderr, _("Installation aborted at user request")
    except Exception, main_e:
        logging.exception(main_e)
        sys.exit(1)

