#!/usr/bin/python 

import sys
sys.path.append('/opt/contrail/lib/python')

import instance_service
import getopt
import logging
import socket

from contrail_lib import rpc_client_instance, uuid_from_string

def add_interface(interface_name, vmi, vm, mac):
    import instance_service.ttypes
    data = instance_service.ttypes.Port(
        uuid_from_string(vmi),
        uuid_from_string(vm),
        interface_name,
        '0.0.0.0',
        [0] * 16,
        mac)

    logging.debug(data)
    rpc = rpc_client_instance()
    if not rpc:
        return
    try:
        rpc.AddPort([data])
    except socket.error:
        logging.error('RPC failure')


def del_interface(vmi):
    rpc = rpc_client_instance()
    if not rpc:
        return
    try:
        rpc.DeletePort(uuid_from_string(vmi))
    except socket.error:
        logging.error('RPC failure')

    logging.info('Deleted virtual-machine-interface uuid = ' + vmi)


def usage():
    print """
    vrouter-ctl [add|del] [interface-name]
        -m | --vm= <virtual-machine-uuid>
        -i | --vmi= <virtual-machine-interface-uuid>
        -a | --mac-address= <address>
"""

def option_check(opt_list):
    for item in opt_list:
        if not item[0]:
            print 'Missing mandatory option: ' + item[1]
            sys.exit(1)

def main(argv):
    try:
        opts, args = getopt.getopt(argv, 'm:i:a:',
                                   ['vm=', 'vmi=', 'mac-address='])
    except getopt.GetoptError, (errno, strerror):
        logging.error('getopt: ' + strerror)
        usage()
        sys.exit(1)

    vm = None
    vmi = None
    mac = None
 
    for opt,arg in opts:
        if opt in ('-m', '--vm'):
            vm = arg
        elif opt in ('-i', '--vmi'):
            vmi = arg
        elif opt in ('-a', '--mac-address'):
            mac = arg

    if len(args) == 0:
        print 'no command specified'
        usage()
        sys.exit(1)

    if args[0] == 'add':
        if len(args) != 2:
            print 'missing interface name'
            usage()
            sys.exit(1)
        option_check([(vmi, 'virtual-machine-interface'),
                      (vm, 'virtual-machine'),
                      (mac, 'mac-address')])
        add_interface(args[1], vmi, vm, mac)
        
    elif args[0] == 'del' or args[0] == 'delete':
        if len(args) != 1:
            usage()
            sys.exit(1)

        option_check([(vmi, 'virtual-machine-interface')])
        del_interface(vmi)

    else:
        usage()
        sys.exit(1)


if __name__ == '__main__':
    logging.basicConfig(filename='/var/log/contrail-ctl.log',
                        level=logging.DEBUG)
    logging.debug('Command: ' + ' '.join(sys.argv))
    main(sys.argv[1:])

