#!/bin/bash

apt-get update && apt-get install -y git nginx python3 python3-pip && pip3 install pyVmomi dotmap
clear
while true; do

    read -p "Enter the AutoVM address (ex: http://backend.domain.com): " domain

    if [ ! -z "$domain" ]; then
        break
    fi

done

while true; do

    read -p "Enter the AutoVM token: " token

    if [ ! -z "$token" ]; then
        break
    fi

done

while true; do

    read -p "Enter the console address (ex: console.domain.com): " console

    if [ ! -z "$console" ]; then
        break
    fi
done

if [ ! -d /etc/autovm ]; then

    mkdir /etc/autovm
fi

cat <<EOF > /etc/autovm/help.py

class Help:

    @staticmethod
    def append(*parts):

        output = ''

        for part in parts:
            output += str(part)

        return output

EOF

cat <<EOF > /etc/autovm/hosts.py

import argparse
import requests

from help import Help
from dotmap import DotMap

from pyVmomi import vim
from pyVim import connect

parser = argparse.ArgumentParser()

arguments = ['address', 'token']

for argument in arguments:
    parser.add_argument(argument)

args = parser.parse_args()

headers = {
    'token': args.token # AutoVM login token
}

address = Help.append(args.address, '/candy/backend/server/index')

response = requests.get(address, headers=headers).json()

if not response:
    raise Exception('Could not find servers')

servers = response.get('data')

if not servers:
    raise Exception('Could not find servers')

for server in servers:

    try:

        server = DotMap(server)

        connection = connect.SmartConnect(host=server.address, user=server.username, pwd=server.password, disableSslCertValidation=True)

        if not connection:
            raise Exception('Could not connect to server')

        content = connection.content

        container = content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True)

        for item in container.view:

            print(item.name)

    except Exception as e:
        print(e)

EOF

function createSubdomain {

    subdomain=$(echo "$1" | md5sum | grep -Eo [a-z0-9]+ | cut -c1-20)

    echo "$subdomain.$console"
}

function createProxy {

cat <<EOF > /etc/nginx/sites-enabled/$2

server {

    location /ticket {
        proxy_pass https://$1;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    server_name $2;
}

EOF

}

function createCertificate {

    certbot --nginx -d $1 --non-interactive --agree-tos --register-unsafely-without-email --quiet --redirect
}

cat <<EOF > /etc/autovm/create.py

import argparse
import requests

from help import Help

parser = argparse.ArgumentParser()

arguments = ['address', 'token', 'host', 'proxy']

for argument in arguments:
    parser.add_argument(argument)

args = parser.parse_args()

headers = {
    'token': args.token # AutoVM login token
}

address = Help.append(args.address, '/candy/backend/proxy/create')

params = {
    'host': args.host, 'proxy': args.proxy, 'port': 443
}

response = requests.post(address, params=params, headers=headers).json()

if not response:
    raise Exception('Could not create proxy')

proxy = response.get('data')

if not proxy:
    raise Exception('Could not create proxy')

print(proxy)

EOF

hosts=$(python3 /etc/autovm/hosts.py "$domain" "$token")

while read host; do

    subdomain=$(createSubdomain "$host")

    createProxy "$host" "$subdomain"

    createCertificate "$subdomain"

    proxy=$(python3 /etc/autovm/create.py "$domain" "$token" "$host" "$subdomain")

    echo "Host: $host Domain: $subdomain"

done <<< "$hosts"
