#!/usr/bin/env python

import argparse
import os.path

import libvirt

templatedir="/usr/share/tripleo/templates"

def main():
    parser = argparse.ArgumentParser(
        description="Configure a kvm virtual machine for the seed image.")
    parser.add_argument('--name', default='seed',
        help='the name to give the machine in libvirt.')
    parser.add_argument('--image',
        help='Use a custom image file (must be qcow2).')
    parser.add_argument('--baremetal-interface', default='brbm',
        help='The interface which bare metal nodes will be connected to.')
    parser.add_argument('--engine', default='kvm',
        help='The virtualization engine to use')
    parser.add_argument('--arch', default='i686',
        help='The architecture to use')
    parser.add_argument('--memory', default='2097152',
        help="Maximum memory for the VM in KB.")
    parser.add_argument('--cpus', default='1',
        help="CPU count for the VM.")
    parser.add_argument('--bootdev', default='hd',
        help="What boot device to use (hd/network).")
    parser.add_argument('--seed', default=False, action='store_true',
        help='Create a seed vm with two interfaces.')
    parser.add_argument('--ovsbridge', default="",
        help='Place the seed public interface on this ovs bridge.')
    parser.add_argument('--libvirt-nic-driver', default='virtio',
        help='The libvirt network driver to use')
    args = parser.parse_args()
    with file(templatedir + '/vm.xml', 'rb') as f:
        source_template = f.read()
    imagefile = '/var/lib/libvirt/images/seed.qcow2'
    if args.image:
        imagefile = args.image
    imagefile = os.path.realpath(imagefile)
    params = {
        'name': args.name,
        'imagefile': imagefile,
        'bmbridge': args.baremetal_interface,
        'engine': args.engine,
        'arch': args.arch,
        'memory': args.memory,
        'cpus': args.cpus,
        'bootdev': args.bootdev,
        'network': '',
        }
    if args.image is not None:
        params['imagefile'] = args.image

    if os.path.exists("/usr/bin/kvm"): # Debian
        params['emulator'] = "/usr/bin/kvm"
    elif os.path.exists("/usr/bin/qemu-kvm"): # Redhat
        params['emulator'] = "/usr/bin/qemu-kvm"

    nicparams = {
        'nicdriver': args.libvirt_nic_driver,
        'bminterface': args.baremetal_interface,
        'ovsbridge': args.ovsbridge,
        }
    if args.seed:
        if args.ovsbridge:
            params['network'] = """
      <interface type='bridge'>
        <source bridge='%(ovsbridge)s'/>
        <virtualport type='openvswitch'/>
        <model type='%(nicdriver)s'/>
        <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
      </interface>""" % nicparams
        else:
            params['network'] = """
      <!-- regular natted network, for access to the vm -->
      <interface type='network'>
        <source network='default'/>
        <model type='%(nicdriver)s'/>
        <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
      </interface>""" % nicparams

    params['bm_network'] = """
      <!-- bridged 'bare metal' network -->
      <interface type='network'>
        <source network='%(bminterface)s'/>
        <model type='%(nicdriver)s'/>
        <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
      </interface>""" % nicparams

    libvirt_template = source_template % params
    conn=libvirt.open("qemu:///system")
    a = conn.defineXML(libvirt_template)
    print ("Created machine %s with UUID %s" % (args.name, a.UUIDString()))

if __name__ == '__main__':
    main()

