# import getpass
# import os

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

# reqs:
#   services: nova, glance, neutron
#   resources: 2 instances, 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
    #
    ###########################################################################

    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

    ###########################################################################
    #
    # 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
    #
    ###########################################################################

    print('Checking for existing worker security group...')
    security_group_name = 'worker'
    security_group_exists = False
    worker_security_group = ''
    for security_group in conn.ex_list_security_groups():
        if security_group.name == security_group_name:
            worker_security_group = security_group
            security_group_exists = True

    if security_group_exists:
        print(('Worker Security Group ' + worker_security_group.name + ' already exists. Skipping creation.'))
    else:
        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)

    print('Checking for existing controller security group...')
    security_group_name = 'control'
    security_group_exists = False
    controller_security_group = ''
    for security_group in conn.ex_list_security_groups():
        if security_group.name == security_group_name:
            controller_security_group = security_group
            security_group_exists = True

    if security_group_exists:
        print(('Controller Security Group ' + controller_security_group.name + ' already exists. Skipping creation.'))
    else:
        controller_security_group = conn.ex_create_security_group('control', 'for services that run on a control node')
        conn.ex_create_security_group_rule(controller_security_group, 'TCP', 22, 22)
        conn.ex_create_security_group_rule(controller_security_group, 'TCP', 80, 80)
        conn.ex_create_security_group_rule(controller_security_group, 'TCP', 5672, 5672,
                                           source_security_group=worker_security_group)

    for security_group in conn.ex_list_security_groups():
        print(security_group)

    ###########################################################################
    #
    # create app-controller
    #
    ###########################################################################

    #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 = '''#!/usr/bin/env bash
    curl -L -s ''' + hsfd_faafo_cloud_init_script + ''' | bash -s -- \
        -i messaging -i faafo -r api
    rabbitmqctl add_user faafo guest
    rabbitmqctl set_user_tags faafo administrator
    rabbitmqctl set_permissions -p / faafo ".*" ".*" ".*"
    '''

    print('Starting new app-controller instance and wait until it is running...')
    instance_controller_1 = conn.create_node(name='app-controller',
                                             image=image,
                                             size=flavor,
                                             networks=[network],
                                             ex_keyname=keypair_name,
                                             ex_userdata=userdata,
                                             ex_security_groups=[controller_security_group])

    conn.wait_until_running(nodes=[instance_controller_1], timeout=120, ssh_interface='private_ips')

    ###########################################################################
    #
    # assign app-controller floating ip
    #
    ###########################################################################

    print('Checking for unused Floating IP...')
    unused_floating_ip = None
    for floating_ip in conn.ex_list_floating_ips():
        if not floating_ip.node_id:
            unused_floating_ip = floating_ip
            break

    if not unused_floating_ip:
        pool = conn.ex_list_floating_ip_pools()[0]
        print(('Allocating new Floating IP from pool: {}'.format(pool)))
        unused_floating_ip = pool.create_floating_ip()

    conn.ex_attach_floating_ip_to_node(instance_controller_1, unused_floating_ip)
    print(('Controller Application will be deployed to http://%s' % unused_floating_ip.ip_address))

    ###########################################################################
    #
    # getting id and ip address of app-controller instance
    #
    ###########################################################################

    # instance should not have a public ip? floating ips are assigned later
    instance_controller_1 = conn.ex_get_node_details(instance_controller_1.id)
    if instance_controller_1.public_ips:
        ip_controller = instance_controller_1.public_ips[0]
    else:
        ip_controller = instance_controller_1.private_ips[0]

    ###########################################################################
    #
    # create app-worker-1
    #
    ###########################################################################

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

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

    conn.wait_until_running(nodes=[instance_worker_1], timeout=120, ssh_interface='private_ips')

    ###########################################################################
    #
    # assign app-worker floating ip
    #
    ###########################################################################

    print('Checking for unused Floating IP...')
    unused_floating_ip = None
    for floating_ip in conn.ex_list_floating_ips():
        if not floating_ip.node_id:
            unused_floating_ip = floating_ip
            break

    if not unused_floating_ip:
        pool = conn.ex_list_floating_ip_pools()[0]
        print(('Allocating new Floating IP from pool: {}'.format(pool)))
        unused_floating_ip = pool.create_floating_ip()

    conn.ex_attach_floating_ip_to_node(instance_worker_1, unused_floating_ip)
    print(('The worker will be available for SSH at %s' % unused_floating_ip.ip_address))

    print('You can use ssh to login to the controller using your private key. After login, you can list available '
          'fractals using "faafo list". To request the generation of new fractals, you can use "faafo create". '
          'You can also see other options to use the faafo example cloud service using "faafo -h".')


if __name__ == '__main__':
    main()