#!/usr/bin/python -tt
#
# Copyright(c) FUJITSU Limited 2007.
#
# Script to set up an cloning guest configuration and kick off an cloning
#
# 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 logging
import virtinst
import virtinst.CloneManager as clmgr
import urlgrabber.progress as progress

from optparse import OptionGroup
import gettext
import locale
import virtinst.cli as cli
from virtinst.cli import fail
from virtinst.User import User

locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(virtinst.gettext_app, virtinst.gettext_dir)
gettext.install(virtinst.gettext_app, virtinst.gettext_dir, unicode=1)

### General input gathering functions
def get_clone_name(new_name, design):
    while 1:
        new_name = cli.prompt_for_input(_("What is the name for the cloned virtual machine?"), new_name)
        try:
            design.clone_name = new_name
            break
        except (ValueError, RuntimeError), e:
            print _("ERROR: "), e
            new_name = None

def get_original_guest(guest, origfile, design):

    origxml = None
    if origfile:
        f = open(origfile, "r")
        origxml = f.read()
        f.close()

    while 1:
        if not origxml:
            guest = cli.prompt_for_input(_("What is the name of the original virtual machine?"), guest)
        try:
            if origxml:
                design.original_xml = origxml
            else:
                design.original_guest = guest
            break
        except (ValueError, RuntimeError), e:
            print _("ERROR: "), e
            guest = None
            origxml = None

def get_clone_macaddr(new_mac, design):
    if new_mac is None:
        pass
    elif new_mac[0] == "RANDOM":
        new_mac = None
    else:
        for i in new_mac:
            design.set_clone_mac(i)

def get_clone_uuid(new_uuid, design):
    if new_uuid is not None:
        design.set_clone_uuid(new_uuid)

def get_clone_diskfile(new_diskfiles, design, conn, preserve=False):
    if new_diskfiles is None:
        new_diskfiles = [None]

    newidx = 0
    for origdev in design.original_devices:
        failed_loop = False
        while 1:
            if not failed_loop:
                if len(new_diskfiles) <= newidx:
                    new_diskfiles.append(None)
                disk = new_diskfiles[newidx]
            else:
                disk = None
            failed_loop = True

            disk = cli.prompt_for_input(_("What would you like to use as the cloned disk (file path) for '%s'?") % origdev, disk)

            # Build disk object for validation
            try:
                d = virtinst.VirtualDisk(path=disk, size=.0001, conn=conn)
            except ValueError, e:
                print _("ERROR: "), e
                continue

            # Prompt if disk file already exists and preserve mode is not used
            if not preserve  and  os.path.exists(d.path):
                warnmsg = _("This will overwrite the existing path "
                            "'%s'!\n") % d.path
                if not cli.prompt_for_yes_or_no(warnmsg + _("Do you really want to use this disk (yes or no)?")):
                    continue

            # Check disk conflicts
            if d.is_conflict_disk(conn) is True:
                warnmsg = _("Disk %s is already in use by another guest!\n") % d.path
                if not cli.prompt_for_yes_or_no(warnmsg + _("Do you really want to use the disk (yes or no)? ")):
                    continue

            design.clone_devices = d.path
            newidx += 1
            break


def get_clone_sparse(sparse, design):
    design.set_clone_sparse(sparse)

def get_preserve(preserve, design):
    design.set_preserve(preserve)


def get_force_target(target, design):
    if target is None:
        pass
    else:
        for i in target:
            design.set_force_target(i)

def parse_args():
    parser = cli.VirtOptionParser()

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

    geng = OptionGroup(parser, _("General Options"))
    geng.add_option("-o", "--original", type="string", dest="original_guest",
                    action="callback", callback=cli.check_before_store,
                    help=_("Name of the original guest; "
                           "The status must be shut off or paused."))
    geng.add_option("", "--original-xml", type="string",
                    dest="original_xml", action="callback",
                    callback=cli.check_before_store,
                    help=_("XML file to use as the original guest."))
    geng.add_option("-n", "--name", type="string", dest="new_name",
                    action="callback", callback=cli.check_before_store,
                    help=_("Name for the new guest"))
    geng.add_option("-u", "--uuid", type="string",
                    dest="new_uuid", action="callback",
                    callback=cli.check_before_store,
                    help=_("New UUID for the clone guest; Default is a "
                           "randomly generated UUID"))
    parser.add_option_group(geng)

    stog = OptionGroup(parser, _("Storage Configuration"))
    stog.add_option("-f", "--file", type="string",
                    dest="new_diskfile", action="callback",
                    callback=cli.check_before_append,
                    help=_("New file to use as the disk image for the "
                           "new guest"))
    stog.add_option("", "--force-copy", type="string",
                    dest="target", action="callback",
                    callback=cli.check_before_append,
                    help=_("Force to copy devices (eg, if 'hdc' is a "
                           "readonly cdrom device, --force-copy=hdc)"))
    stog.add_option("", "--nonsparse", action="store_false",
                    default=True, dest="sparse",
                    help=_("Do not use a sparse file for the clone's "
                           "disk image"))
    stog.add_option("", "--preserve-data", action="store_false",
                    default=True, dest="preserve",
                    help=_("Preserve a new file to use as the disk image "
                           "for the new guest"))
    parser.add_option_group(stog)

    netg = OptionGroup(parser, _("Networking Configuration"))
    netg.add_option("-m", "--mac", type="string",
                    dest="new_mac", action="callback",
                    callback=cli.check_before_append,
                    help=_("New fixed MAC address for the clone guest. "
                           "Default is a randomly generated MAC"))
    parser.add_option_group(netg)

    misc = OptionGroup(parser, _("Miscellaneous Options"))
    misc.add_option("-d", "--debug", action="store_true", dest="debug",
                      help=_("Print debugging information"))
    misc.add_option("", "--force", action="store_true", dest="force",
                      help=_("Do not prompt for input. Answers yes where "
                             "applicable, terminates for all other prompts"),
                      default=False)
    parser.add_option_group(misc)

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

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

    cli.setupLogging("virt-clone", options.debug)
    cli.set_force(options.force)

    if not User.current().has_priv(User.PRIV_CLONE, options.connect):
        fail(_("Must be privileged to clone Xen guests"))

    conn = cli.getConnection(options.connect)
    design = clmgr.CloneDesign(connection=conn)

    try:
        get_clone_diskfile(options.new_diskfile, design, conn,
                           not options.preserve)
        get_clone_macaddr(options.new_mac, design)
        get_original_guest(options.original_guest, options.original_xml,
                           design)
        get_clone_name(options.new_name, design)
        get_clone_uuid(options.new_uuid, design)
        get_clone_sparse(options.sparse, design)
        get_force_target(options.target, design)
        get_preserve(options.preserve, design)

        # This determines the devices that need to be cloned, so that
        # get_clone_diskfile knows how many new disk paths it needs
        design.setup_original()

        get_clone_diskfile(options.new_diskfile, design, conn,
                           not options.preserve)

        # setup design object
        design.setup()

        # start cloning
        meter = progress.TextMeter()
        clmgr.start_duplicate(design, meter)

        print _("\nClone '%s' created successfully.") % design.clone_name
        logging.debug("end clone")
    except RuntimeError, e:
        fail(e)
    except SystemExit, e:
        sys.exit(e.code)
    except Exception, e:
        fail(e)

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)

