#   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 os
from pathlib import Path
import yaml
from common_helpers import get_prometheus_info


# Prometheus host and port
(prometheus_host, prometheus_port) = get_prometheus_info()

# VIM configuration
cloud_type = os.environ.get("CLOUD_TYPE", "openstack")
if cloud_type == "openstack":
    # Openstack VIM
    vim_account_type = "openstack"
    vim_name_prefix = "basic01"
    # Get credentias from Openstack Clouds file
    os_cloud = os.environ.get("OS_CLOUD")
    clouds_file_paths = ["./clouds.yaml", str(Path.home()) + "/.config/openstack/clouds.yaml", "/etc/openstack/clouds.yaml"]
    for path in clouds_file_paths:
        clouds_file_path = Path(path)
        if clouds_file_path.exists():
            break
    if not clouds_file_path.exists():
        raise Exception("Openstack clouds file not found")
    with clouds_file_path.open() as clouds_file:
        clouds = yaml.safe_load(clouds_file)
        if not os_cloud in clouds["clouds"]:
            raise Exception("Openstack cloud '" + os_cloud + "' not found")
        cloud = clouds["clouds"][os_cloud]
        if not "username" in cloud["auth"]:
            raise Exception("Username not found in Openstack cloud '" + os_cloud + "'")
        vim_user = cloud["auth"]["username"]
        if not "password" in cloud["auth"]:
            raise Exception("Password not found in Openstack cloud '" + os_cloud + "'")
        vim_password = cloud["auth"]["password"]
        if not "auth_url" in cloud["auth"]:
            raise Exception("Auth url not found in Openstack cloud '" + os_cloud + "'")
        vim_auth_url = cloud["auth"]["auth_url"]
        if not "project_name" in cloud["auth"]:
            raise Exception("Project name not found in Openstack cloud '" + os_cloud + "'")
        vim_tenant = cloud["auth"]["project_name"]
        vim_user_domain_name = cloud["auth"]["user_domain_name"] if "user_domain_name" in cloud["auth"] else None
        vim_project_domain_name = cloud["auth"]["project_domain_name"] if "project_domain_name" in cloud["auth"] else None
        vim_insecure = True if "verify" in cloud and not cloud["verify"] else None
    
    # Extra config
    vim_config_dict = {}
    vim_config_dict["vim_network_name"] = os.environ.get("VIM_MGMT_NET")
    if vim_project_domain_name:
        vim_config_dict["project_domain_name"] = vim_project_domain_name
    if vim_user_domain_name:
        vim_config_dict["user_domain_name"] = vim_user_domain_name
    if vim_insecure:
        vim_config_dict["insecure"] = True
    vim_config = "'{}'".format(yaml.safe_dump(vim_config_dict, default_flow_style=True, width=10000).rstrip('\r\n'))

elif cloud_type == "azure":
    # Azure VIM
    vim_account_type = "azure"
    vim_name_prefix = "basic01"
    vim_auth_url = "http://www.azure.com"
    vim_user = os.environ.get("AZURE_CLIENT_ID")
    vim_password = os.environ.get("AZURE_SECRET")
    vim_tenant = os.environ.get("AZURE_TENANT")

    # Extra config
    vim_config_dict = {}
    if "RESOURCE_GROUP" in os.environ:
        vim_config_dict["resource_group"] = os.environ.get("RESOURCE_GROUP")
    if "AZURE_REGION" in os.environ:
        vim_config_dict["region_name"] = os.environ.get("AZURE_REGION")
    if "AZURE_SUBSCRIPTION_ID" in os.environ:
        vim_config_dict["subscription_id"] = os.environ.get("AZURE_SUBSCRIPTION_ID")
    if "VNET_NAME" in os.environ:
        vim_config_dict["vnet_name"] = os.environ.get("VNET_NAME")
    if "AZURE_FLAVORS_PATTERN" in os.environ:
        vim_config_dict["flavors_pattern"] = os.environ.get("AZURE_FLAVORS_PATTERN")
    vim_config = "'{}'".format(yaml.safe_dump(vim_config_dict, default_flow_style=True, width=10000).rstrip('\r\n'))

else:
    raise Exception("VIM type not supported: '" + cloud_type + "'")
