# import getpass
# import os
# import libcloud.security

import time
from libcloud.compute.providers import get_driver
from libcloud.compute.types import Provider

# reqs:
#   services: nova, glance, neutron
#   resources: 2 instances (m1.small), 2 floating ips (1 keypair, 2 security groups)

# Please use 1-29 for X in the following variable to specify your group number. (will be used for the username,
# project etc., as coordinated in the lab sessions)

group_number = X


# web service endpoint of the private cloud infrastructure
auth_url = 'https://private-cloud.informatik.hs-fulda.de:5000'
# your username in OpenStack
auth_username = 'CloudComp' + str(group_number)
# your project in OpenStack
project_name = 'CloudComp' + str(group_number)
# A network in the project the started instance will be attached to
project_network = 'CloudComp' + str(group_number) + '-net'

# The image to look for and use for the started instance
#ubuntu_image_name = "Ubuntu 20.04 - Focal Fossa - 64-bit - Cloud Based Image"
ubuntu_image_name = "Ubuntu 22.04 - Jammy Jellyfish - 64-bit - Cloud Based Image"

# The public key to be used for SSH connection, please make sure, that you have the corresponding private key
#
# id_rsa.pub should look like this (standard sshd pubkey format):
# ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAw+J...F3w2mleybgT1w== user@HOSTNAME

#keypair_name = 'CloudComp30-keypair'
keypair_name = "srieger-pub"
pub_key_file = '~/.ssh/id_rsa.pub'

flavor_name = 'm1.small'


# default region
region_name = 'RegionOne'
# domain to use, "default" for local accounts, "hsfulda" for RZ LDAP, e.g., using fdaiXXXX as auth_username
domain_name = "default"


def main():
    ###########################################################################
    #
    # get credentials
    #
    ###########################################################################

    # if "OS_PASSWORD" in os.environ:
    #     auth_password = os.environ["OS_PASSWORD"]
    # else:
    #     auth_password = getpass.getpass("Enter your OpenStack password:")
    auth_password = "demo"

    ###########################################################################
    #
    # create connection
    #
    ###########################################################################

    # libcloud.security.VERIFY_SSL_CERT = False

    provider = get_driver(Provider.OPENSTACK)
    conn = provider(auth_username,
                    auth_password,
                    ex_force_auth_url=auth_url,
                    ex_force_auth_version='3.x_password',
                    ex_tenant_name=project_name,
                    ex_force_service_region=region_name,
                    ex_domain_name=domain_name)

    ###########################################################################
    #
    # get image, flavor, network for instance creation
    #
    ###########################################################################

    images = conn.list_images()
    image = ''
    for img in images:
        if img.name == ubuntu_image_name:
            image = img

    flavors = conn.list_sizes()
    flavor = ''
    for flav in flavors:
        if flav.name == flavor_name:
            flavor = conn.ex_get_size(flav.id)

    networks = conn.ex_list_networks()
    network = ''
    for net in networks:
        if net.name == project_network:
            network = net

    ###########################################################################
    #
    # get fixed a ip for service and api instance
    # (better would be shared IP for the cluster etc.) 
    #
    ###########################################################################

    # find service instance
    for instance in conn.list_nodes():
        if instance.name == 'app-services':
            services_ip = instance.private_ips[0]
            print(('Found app-services fixed IP to be: ', services_ip)) 
        if instance.name == 'app-api-1':
            api_1_ip = instance.private_ips[0]
            print(('Found app-api-1 fixed IP to be: ', api_1_ip)) 

    ###########################################################################
    #
    # create keypair dependency
    #
    ###########################################################################

    print('Checking for existing SSH key pair...')
    keypair_exists = False
    for keypair in conn.list_key_pairs():
        if keypair.name == keypair_name:
            keypair_exists = True

    if keypair_exists:
        print(('Keypair ' + keypair_name + ' already exists. Skipping import.'))
    else:
        print('adding keypair...')
        conn.import_key_pair_from_file(keypair_name, pub_key_file)

    for keypair in conn.list_key_pairs():
        print(keypair)
    
    ###########################################################################
    #
    # create security group dependency
    #
    ###########################################################################

    def get_security_group(connection, security_group_name):
        """A helper function to check if security group already exists"""
        print(('Checking for existing ' + security_group_name + ' security group...'))
        for security_grp in connection.ex_list_security_groups():
            if security_grp.name == security_group_name:
                print(('Security Group ' + security_group_name + ' already exists. Skipping creation.'))
                return security_grp
        return False

    if not get_security_group(conn, "worker"):
        worker_security_group = conn.ex_create_security_group('worker', 'for services that run on a worker node')
        conn.ex_create_security_group_rule(worker_security_group, 'TCP', 22, 22)
    else:
        worker_security_group = get_security_group(conn, "worker")

    for security_group in conn.ex_list_security_groups():
        print(security_group)
        
    ###########################################################################
    #
    # create worker instances
    #
    ###########################################################################

    #hsfd_faafo_cloud_init_script = 'https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh'
    # testing / faafo dev branch:
    hsfd_faafo_cloud_init_script = 'https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/branch/dev_faafo/faafo/contrib/install.sh'

    userdata_worker = '''#!/usr/bin/env bash
    curl -L -s ''' + hsfd_faafo_cloud_init_script + ''' | bash -s -- \
        -i faafo -r worker -e 'http://%(api_1_ip)s' -m 'amqp://faafo:guest@%(services_ip)s:5672/'
    ''' % {'api_1_ip': api_1_ip, 'services_ip': services_ip}

    # userdata-api-2 = '''#!/usr/bin/env bash
    # curl -L -s ''' + hsfd_faafo_cloud_init_script + ''' | bash -s -- \
    #     -i faafo -r worker -e 'http://%(api_2_ip)s' -m 'amqp://faafo:guest@%(services_ip)s:5672/'
    # ''' % {'api_2_ip': api_2_ip, 'services_ip': services_ip}

    print('Starting new app-worker-3 instance and wait until it is running...')
    instance_worker_3 = conn.create_node(name='app-worker-3',
                                         image=image, size=flavor,
                                         networks=[network],
                                         ex_keyname=keypair_name,
                                         ex_userdata=userdata_worker,
                                         ex_security_groups=[worker_security_group])

    print(instance_worker_3)

if __name__ == '__main__':
    main()