#!/usr/bin/env python3
from pyVmomi import vim
import pyVim.connect
import atexit
import argparse
import time
import siteconf
 
site_conf = siteconf.read()


def get_args():
    parser = argparse.ArgumentParser(
        description='Set VM network')

    parser.add_argument('-s', '--site',
                        required=True,
                        action='store',
                        help='name of the site to connect to')

    parser.add_argument('-v', '--vm',
                        required=True,
                        action='store',
                        help='vm to configure')

    parser.add_argument('-n', '--network',
                        required=True,
                        action='store',
                        help='new network')

    args = parser.parse_args()
    return args


def get_obj(content, vimtype, name):
    """
    Return an object by name, if name is None the
    first found object is returned
    """
    obj = None
    container = content.viewManager.CreateContainerView(
        content.rootFolder, vimtype, True)
    for c in container.view:
        if name:
            if c.name == name:
                obj = c
                break
        else:
            obj = c
            break

    return obj


def main():
    args = get_args()

    if not args.site in site_conf:
        print(f"site not found: {args.site}")
        exit(1)
    host = site_conf[args.site]['vcenter']
    user = site_conf[args.site]['vcenter_user']
    passwd = site_conf[args.site]['vcenter_passwd']

    si = pyVim.connect.SmartConnect(
        host = host,
        user = user,
        pwd = passwd,
        disableSslCertValidation = True
        )
    atexit.register(pyVim.connect.Disconnect, si)
    content = si.RetrieveContent()

    vm = get_obj(content, [vim.VirtualMachine], args.vm)
    if not vm:
        print("vm not found")
        exit(1)
    net = get_obj(content, [vim.Network], args.network)
    if not net:
        print("network not found")
        exit(1)

    device_change = []
    for dev in vm.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualEthernetCard):
            nicspec = vim.vm.device.VirtualDeviceSpec()
            nicspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
            nicspec.device = dev
            nicspec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
            nicspec.device.backing.network = net
            nicspec.device.backing.deviceName = args.network
            nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
            nicspec.device.connectable.startConnected = True
            nicspec.device.connectable.allowGuestControl = True
            nicspec.device.connectable.connected = True
            device_change.append(nicspec)
            break

    config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
    task = vm.ReconfigVM_Task(config_spec)
    while task.info.state == vim.TaskInfo.State.running:
        time.sleep(1)
    print("network changed")


if __name__ == "__main__":
    main()

# vim: set tabstop=4 shiftwidth=4 expandtab smarttab:
