#!/usr/bin/env python
USAGE = """
SYNOPSIS
    stop_clone_guests.py config.cfg
DESCRIPTION
    This script shuts down the clones created by id_clone_hosts.py, using the
    same .cfg file.

    Please refer to the id_clone_hosts.py help for more information."""
import sys
from common import parse_cfg, is_defined_guest, is_active_guest


if not len(sys.argv) == 2:
    print USAGE
    sys.exit(1)

conn, machines_to_clone, cfg, xmlfilepath = parse_cfg(sys.argv[1])

clone_names = [cfg.get(orig_name, "clone_name")
               for orig_name in machines_to_clone]

defined_clones_names = [clone_name
                        for clone_name in clone_names
                        if is_defined_guest(conn, clone_name)]

for clone_name in defined_clones_names:
    guest = conn.lookupByName(clone_name)
    if guest.isActive():
        guest.destroy()
                                              cfg.get(orig, "clone_name")))
                     for orig in machines_to_clone]

    tree = ElementTree.ElementTree()
    tree.parse(xmlfilepath)

    dhcp_section = tree.find("ip/dhcp")
    for orig_name, mac in mac_addresses:
        hostname = cfg.get(orig_name, "hostname")
        ip = cfg.get(orig_name, "ip")
        element = ElementTree.Element("host", {"mac": mac,
                                               "name": hostname,
                                               "ip": ip})
        dhcp_section.insert(0, element)

    netxml = ElementTree.tostring(tree.getroot())
    conn.networkCreateXML(netxml)


if __name__ == "__main__":
    if not len(sys.argv) == 2:
        print USAGE
        sys.exit(1)

    configfilepath = sys.argv[1]
    conn, machines_to_clone, cfg, xmlfilepath = parse_cfg(configfilepath)

    # Clone the machines
    for machine in machines_to_clone:
        clone(conn, machine, cfg)