#!/usr/bin/env python3
import json
import random
import string
import os

inventory  = None
groupnames = None
groupusers = None

def random_ascii_string(n: int):
    return ''.join(random.choices(string.ascii_letters, k=32))

def json_load(filename: str):
    with open(filename, 'r') as f:
        return json.load(f)

def generate_vars(host_ip: str):
    print(f"Generating host vars for {host_ip}...")
    host_var_path = f'host_vars/{host_ip}.json'

    group_name = groupnames[host_ip]
    users = groupusers.get(group_name, {})
    for user in users.values():
        user["mysql_password"] = random_ascii_string(32)

    host_vars = {}

    if os.path.exists(host_var_path):
        print("Host vars already exist, only adding/removing users...")
        with open(host_var_path, 'r') as f:
            print(f"Opening host vars: {host_var_path}")
            host_vars = json.load(f)

        # Create new users...
        for uid, user in users.items():
            if uid not in host_vars['users']:
                host_vars['users'][uid] = user
            else:
                host_vars['users'][uid]['name'] = user['name']

        # Remove deleted users...
        for uid in [*host_vars['users'].keys()]:
            if uid not in users:
                del host_vars['users'][uid]

        host_vars['domain_name'] = f'{group_name}.webtech-uva.nl'

    else:
        host_vars = {
            'pma_blowfish': random_ascii_string(32),
            'mysql_root_pw': random_ascii_string(32),
            'domain_name': f'{group_name}.webtech-uva.nl',
            'users': users
        }


    with open(f'host_vars/{host_ip}.json', 'w') as f:
        json.dump(host_vars, f, indent=4)


def main():
    global inventory, groupnames, groupusers
    os.makedirs('./host_vars', exist_ok=True)
    inventory = json_load('inventory.json')
    groupnames = json_load('groupnames.json')
    groupusers = json_load('../student_data.json')

    for host_ip in inventory['servers']['hosts'].keys():
        generate_vars(host_ip)

if __name__ == '__main__':
    main()
