def main(argv=None):
    if argv is None:
        argv = sys.argv

    parser = argparse.ArgumentParser()

    parser.add_argument('configuration_file', type=str)
    parser.add_argument('-H', '--host', type=str, default='127.0.0.1',
        help='Resource manager host')
    parser.add_argument('-p', '--port', type=int, default=8002,
        help='Resource manager port')

    args = parser.parse_args(argv[1:])

    configuration_file_path = args.configuration_file
    target_host = args.host
    resource_manager_url = 'http://{}:{}'.format(target_host, args.port)

    with open(configuration_file_path) as data_file:
        credentials = json.load(data_file)["credentials"]

    for credential in credentials:
        print(credential)

        username = credential["username"]
        project_name = credential["project_name"]
        infrastructure_name = credential["infrastructure"]
        credential_name = credential["name"]
        password = getpass.getpass(
            "Please provide the OpenStack password for ({}, {})@{}:".format(
                username, project_name, infrastructure_name
        ))

        # Creating a new user if needed
        # user_dict = {
        #     "username": username,
        #     "password": "******",
        #     "project": project_name
        # }
        # r = requests.post(
        #     url="{}/users/".format(resource_manager_url),
        #     json=user_dict,
        #     headers=dibbs_auth.client_auth_headers(USERNAME),
        # )

        # Get the key of the current user
        r = requests.get(
            "{}/rsa_public_key/{}".format(resource_manager_url, USERNAME),
            headers=dibbs_auth.client_auth_headers(USERNAME),
        )

        if r.status_code != 200:
            print("could not retrieve the public key for user %s :(" % (user_id,))
            print('HTTP {}'.format(r.status_code))
            print(r.content[:1000])
            return 1

        public_key_str = r.json()["public_key"]
        public_key = RSA.importKey(public_key_str)

        print("Storing credentials using below key:")
        print(public_key_str)

        # Upload new credentials for the new user
        credentials = {
            "username": username,
            "password": password,
            "project": project_name
        }
        message = json.dumps(credentials).encode('utf-8')
        cipher = PKCS1_OAEP.new(public_key)
        cipher_text = cipher.encrypt(message)

        cipher_text_b64 = base64.b64encode(cipher_text)

        # Upload the credentials to the resource_manager

        r = requests.post(
            "{}/credentials/".format(resource_manager_url),
            json={
                "credentials": cipher_text_b64,
                "site_name": infrastructure_name,
                "name": credential_name,
                "user": USERNAME,
            },
            headers=dibbs_auth.client_auth_headers(USERNAME),
        )

        print(r.status_code)
        print(r.json())
def main(argv=None):
    """Create appliances to demonstrate the architecture"""
    if argv is None:
        argv = sys.argv

    configuration_file_path = None
    if len(argv) > 1:
        configuration_file_path = argv[1]

    if configuration_file_path is None:
        print("No configuration file passed as a parameter :-(")
        return 1

    with open(configuration_file_path) as data_file:
        infrastructures = json.load(data_file)["infrastructures"]

    for infrastructure in infrastructures:
        infrastructure_name = infrastructure["name"]
        infrastructure_url = infrastructure["contact_url"]
        infrastructure_type = infrastructure["type"]

        # Creation of site
        site_dict = {
            "name": infrastructure_name,
            "type": infrastructure_type,
            "contact_url": infrastructure_url
        }
        r = requests.post(
            "{}/sites/".format(appliance_registry_url),
            json=site_dict,
            headers=client_auth_headers('alice', 'pass'),
        )
        print(
            "- creation of site %s => %s %s" % (
                infrastructure_name, r.status_code, r.json() if r.status_code >= 400 else ""))

        skip_actions_creation = False
        if len(argv) > 1:
            if argv[1] == "skip":
                skip_actions_creation = True

        # If needed, create actions
        if not skip_actions_creation:
            actions = ["configure_node", "prepare_node", "update_master_node", "user_data", "update_hosts_file", "heat_template"]

            for action in actions:
                # Creating a new action
                action_dict = {
                    "name": action
                }
                r = requests.post(
                    "{}/actions/".format(appliance_registry_url),
                    json=action_dict,
                    headers=client_auth_headers('alice', 'pass'),
                )
                print(
                    "- creation of action %s => %s %s" % (
                        action, r.status_code, r.json() if r.status_code >= 400 else ""))

        # Create appliances
        for dirname, dirnames, filenames in os.walk("appliances"):
            # print path to all subdirectories first.
            for subdirname in dirnames:
                appliance_name = subdirname
                complete_path = os.path.join(dirname, subdirname)
                metadata_keys = ["description", "image", "image_name"]

                # Collect appliance metadata
                appliance_metadata = {
                    "description": "",
                    "image": "",
                    "image_name": ""
                }
                for metadata_key in metadata_keys:
                    metdata_file_address = "%s/%s.txt" % (complete_path, metadata_key)
                    if os.path.isfile(metdata_file_address):
                        with open(metdata_file_address) as f:
                            content = f.read()
                            appliance_metadata[metadata_key] = content

                # Create a new appliance
                appliance_dict = {
                    "name": appliance_name,
                    "logo_url": appliance_metadata["image"],
                    "description": appliance_metadata["description"]
                }

                r = requests.post(
                    "{}/appliances/".format(appliance_registry_url),
                    json=appliance_dict,
                    headers=client_auth_headers('alice', 'pass'),
                )
                print("- creation of appliance %s => %s %s" % (
                    appliance_name, r.status_code, r.json() if r.status_code >= 400 else ""))

                # Create an appliance implementation for the given site
                sites = [infrastructure_name]

                # Create an implementation of the appliance for each given site
                for site in sites:
                    appliance_impl_name = "%s_%s" % (
                        appliance_name, site) if appliance_name != "common" else "common"
                    appliance_impl_logo_address = "%s/%s_image.txt" % (complete_path, appliance_impl_name)
                    # if os.path.isfile(appliance_impl_logo_address) or appliance_impl_name == "common":
                    appliance_impl_dict = {
                        "name": appliance_impl_name,
                        "appliance": appliance_name,
                        "image_name": appliance_metadata["image_name"] if appliance_name != "common" else "n.a.",
                        "site": site,
                        "logo_url": appliance_impl_logo_address
                    }
                    r = requests.post(
                        "{}/appliances_impl/".format(appliance_registry_url),
                        json=appliance_impl_dict,
                        headers=client_auth_headers('alice', 'pass'),
                    )
                    print("  - creation of appliance_impl %s => %s %s" % (
                        appliance_impl_name, r.status_code, r.json() if r.status_code >= 400 else ""))

                    # Create an instance of each script for each appliance implementation
                    for script_dirname, script_dirnames, script_filenames in os.walk("%s" % (complete_path)):
                        for script_filename in script_filenames:
                            script_file_address = "%s/%s" % (complete_path, script_filename)
                            if not "heat_template.jinja2" in script_file_address:
                                continue
                            with open(script_file_address) as script_f:
                                script_content = script_f.read()
                            action_name = re.sub(r'.*/', '', re.sub(r'.jinja2', '', script_file_address))
                            print(action_name)
                            script_dict = {
                                "code": script_content,
                                "appliance": appliance_impl_name if appliance_name != "common" else appliance_name,
                                "action": action_name
                            }
                            r = requests.post(
                                "{}/scripts/".format(appliance_registry_url),
                                json=script_dict,
                                headers=client_auth_headers('alice', 'pass'),
                            )
                            print("    - creation of script_impl %s => %s %s" % (
                                action_name, r.status_code, r.json() if r.status_code >= 400 else ""))
    return 0