#==============================================================================
# Copyright 2013 Citrix Systems, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#==============================================================================
import requests
import win32com.client

class AmazonAdaptor:

    def instance_identity_document_url(self):
        return 'http://169.254.169.254/latest/dynamic/instance-identity/document'

    def instance_identity_signature_url(self):
        return 'http://169.254.169.254/latest/dynamic/instance-identity/signature'

    def instance_id_url(self):
        return 'http://169.254.169.254/latest/meta-data/instance-id'

    def iam_security_credentials_url(self, name):
        return 'http://169.254.169.254/latest/meta-data/iam/security-credentials/%s' % name

    def region_url(self, region):
        return 'https://cloudformation.%s.amazonaws.com' % region

    def region_url_regex(self):
        return r'https://cloudformation.([\w\d-]+).amazonaws.com'

class CloudPlatformAdaptor:

    def __init__(self, server):
        self.baseUrl = 'http://{0}/stackmate/'.format(server)

    def instance_identity_document_url(self):
        return self.baseUrl + 'instance-identity/document'

    def instance_identity_signature_url(self):
        return self.baseUrl + 'instance-identity/signature'

    def instance_id_url(self):
        return self.baseUrl + 'meta-data/instance-id'

    def iam_security_credentials_url(self, name):
        return self.baseUrl + 'meta-data/iam/security-credentials/%s' % name

    def region_url(self, region):
        return self.baseUrl + 'region/%s' % region

    def region_url_regex(self):
        return r'{0}region/([\w\d-]+)'.format( self.baseUrl)

def get_dhcp_servers():
    """Get a list of all the DHCP servers configured for the system"""
    result = []
    wmi = win32com.client.Dispatch("WbemScripting.SWbemLocator")
    cim = wmi.ConnectServer(".", "root\cimv2")
    adaptors = cim.ExecQuery("SELECT * from Win32_NetworkAdapterConfiguration where IPEnabled = 'true'")
    for adaptor in adaptors:
        if adaptor.DHCPServer != None:
            result.append(adaptor.DHCPServer)
    return result

def can_get(url):
    """Return true if the URL is accessible via GET."""
    try:
        resp = requests.get(url)
        return True
    except IOError:
       return False

def is_ec2():
    """Try to figure out if this is an EC2 instance by looking for the userdata/metadata server."""
    return can_get("http://169.254.169.254/latest")

Adaptor = None

##if (is_ec2()):
##    Adaptor = AmazonAdaptor()
##else:
##   for dhcp_server in get_dhcp_servers():
##        if can_get("http://%s/latest/user-data"):
##            Adaptor = CloudPlatformAdaptor(dhcp_server)

# Use test server
if Adaptor == None:
    Adaptor = CloudPlatformAdaptor("10.70.176.50")
    ##raise Exception("No UserData service found")






@@ -1545,32 +1545,1064 @@
 atformAdaptor:%0A%0A
+    def __init__(self, server):%0A        self.server = server%0A        self.baseUrl = 'http://%7B0%7D/latest/meta-data/'.format(server)%0A%0A    # Content used for CFN_V1 authentication header to CFN server. This impl is temporary%0A    def instance_identity_document_url(self):%0A        return self.baseUrl + 'instance-id'%0A%0A    # Content used for CFN_V1 authentication header to CFN server. This impl is temporary.%0A    def instance_identity_signature_url(self):%0A        return self.baseUrl + 'instance-id'%0A%0A    def instance_id_url(self):%0A        return self.baseUrl + 'instance-id'%0A%0A    # Unused ?%0A    def iam_security_credentials_url(self, name):%0A        return self.baseUrl + 'meta-data/iam/security-credentials/%25s' %25 name%0A%0A    # CFN Server address: a DescribeStackResource will be made to this Url. Needs Impl!!!%0A    def region_url(self, region):%0A        return self.baseUrl + 'region/%25s' %25 region%0A%0A    def region_url_regex(self):%0A        return r'%7B0%7Dregion/(%5B%5Cw%5Cd-%5D+)'.format( self.baseUrl)%0A%0A# Adaptor for local testing%0Aclass TestAdaptor:%0A%0A
     def __init__
@@ -4109,16 +4109,52 @@
 = None%0A%0A
+## (removed because it is too slow)%0A
 ##if (is
@@ -4202,21 +4202,19 @@
 ##else:%0A
+%0A
 ##
-   
 for dhcp
@@ -4246,21 +4246,16 @@
 rs():%0A##
-     
    if ca
@@ -4282,28 +4282,37 @@
 est/
-user
+meta
 -data%22
+ %25 dhcp_server
 ):%0A##
-     
     
@@ -4362,26 +4362,101 @@
 er)%0A
-%0A# Use test server
+##       break%0A%0A# Use test adaptor if not in CS environment (requires emulator to be running)
 %0Aif 
@@ -4482,37 +4482,28 @@
   Adaptor = 
-CloudPlatform
+Test
 Adaptor(%2210.

Add adaptor layer for AWS/CloudStack abstraction