import time, datetime, os, sys
from pyvcloud.vcloudair import VCA

if False:
    import logging
    import httplib
    httplib.HTTPConnection.debuglevel = 1
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)
    requests_log = logging.getLogger("requests.packages.urllib3")
    requests_log.setLevel(logging.DEBUG)
    requests_log.propagate = True

def diff(a, b):
    b = set(b)
    return [aa for aa in a if aa not in b]

host = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
org = sys.argv[4]
vdc_name = sys.argv[5]
network_name = sys.argv[6]
instance = sys.argv[7]
# vapp_name = sys.argv[8]

# print host
# print username
# print password
# print org
# print vdc_name
# print network_name
# print instance

#sample login sequence on vCloud Air On Demand
vca = VCA(host=host, username=username, service_type='ondemand', version='5.7', verify=True)

#first login, with password
result = vca.login(password=password)

#then login with password and instance id, this will generate a session_token
result = vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)

#next login, with token, org and org_url, no password, it will retrieve the organization
result = vca.login_to_instance(instance=instance, password=None, token=vca.vcloud_session.token, org_url=vca.vcloud_session.org_url)

#this tests the vca token
result = vca.login(token=vca.token)
network = vca.get_network(vdc_name, network_name)

# vapp = vca.get_vapp(vca.get_vdc(vdc_name), vapp_name)
# internal_ip = vapp.get_vms_network_info()[0][0]['ip']

internal_ip='192.168.109.3'

gateway = vca.get_gateways(vdc_name)[0]
used_ips = gateway.get_public_ips()
task = gateway.allocate_public_ip()
task_result = vca.block_until_completed(task)

gateway = vca.get_gateways(vdc_name)[0]
public_ip = diff(gateway.get_public_ips(), used_ips)[0]
gateway.add_nat_rule('DNAT', public_ip, 22, internal_ip, 22, 'Tcp')
gateway.add_nat_rule('DNAT', public_ip, 80, internal_ip, 80, 'Tcp')
gateway.add_nat_rule('DNAT', public_ip, 443, internal_ip, 443, 'Tcp')
gateway.add_nat_rule('SNAT', internal_ip, -1, public_ip, -1, 'Tcp')
task = gateway.save_services_configuration()
task_result = vca.block_until_completed(task)
gateway = vca.get_gateways(vdc_name)[0]
gateway.add_fw_rule(True, "anythinggoes", 'allow', 'Any', 'Any', 'any', 'Any', 'any', True)
task = gateway.save_services_configuration()
task_result = vca.block_until_completed(task)

print (internal_ip+","+public_ip) #use this ip to connect to ops manager
