#!/usr/bin/env python3
# File: generate-systemd-vms.py
# 
# Description: This file generates the systemd.service files that run our VM's
# 
# Package: AniNIX/Ubiqtorate
# Copyright: WTFPL
# 
# Author: DarkFeather <darkfeather@aninix.net>

import os
import shutil
import sys
import yaml

filepath="roles/Node/files/vm-definitions/"

def WriteVMFile(content,hosttype,hostclass):
    ### Create the service files for the hosts
    # param content: the yaml content to parse
    # param hosttype: managed or unmanaged
    # param hostclass: the type of host as classified in the yaml

    global filepath

    for host in content['all']['children'][hosttype]['children'][hostclass]['hosts']:

        cores = 0
        memory = 0
        vnc = 0
        disks = ''
        mac = ''
        bridge = ''

        # Make sure the host definition has all the critera
        try:
            cores = str(content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['cores'])
            memory = str(content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['memory'])
            vnc = str(content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['vnc'])
            disks = ' '.join(content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['disks'])
            mac = content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['mac']
            bridge = content['all']['children'][hosttype]['children'][hostclass]['hosts'][host]['bridge']
        except Exception as e:
            print('Host ' + host + " doesn't have the attributes needed to be a VM -- skipping.")
            print(e) 
            1 == 1

        # Write the file.
        with open(filepath+host+'-vm.service','w') as vmfile:
            vmfile.write('[Unit]\n')
            vmfile.write('Description=AniNIX/' + host + '\n')
            vmfile.write('After=network.target\n')
            vmfile.write('\n')
            vmfile.write('[Service]\n')
            vmfile.write('ExecStart=/usr/sbin/qemu-system-x86_64 -name AniNIX/' + host + ' -machine type=pc,accel=kvm')
            if 'uefi' in content['all']['children'][hosttype]['children'][hostclass]['hosts'][host].keys(): vmfile.write(' -bios /usr/share/edk2-ovmf/x64/OVMF.fd')
            vmfile.write(' -cpu qemu64 -smp ' + cores + ' ' + disks + ' -net nic,macaddr=' + mac + ',model=virtio -net bridge,br=' + bridge + ' -vga std -nographic -vnc :' + str(vnc) + ' -m size=' + str(memory) + 'G -device virtio-rng-pci\n')
            vmfile.write('ExecReload=/bin/kill -HUP $MAINPID\n')
            vmfile.write('KillMode=process\n')
            vmfile.write('Restart=always\n')
            vmfile.write('User=root\n')
            vmfile.write('Group=root\n')
            vmfile.write('\n')
            vmfile.write('[Install]\n')
            vmfile.write('WantedBy=multi-user.target\n')
            print(host+'-vm.service')

def GenerateFiles(file):
    ### Open the file and parse it
    # param file: the file to work on
    
    global filepath

    try:
        shutil.rmtree(filepath)
    except:
        1 == 1
    finally:
        os.mkdir(filepath)

    # Parse the yaml
    with open(file, 'r') as stream:
        content = yaml.safe_load(stream)

        # Add service files for each host
        WriteVMFile(content,'managed','virtual')
        WriteVMFile(content,'unmanaged','ovas')
        #WriteVMFile(content,'unmanaged','appliances')

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("You need to supply an inventory file.")
        sys.exit(1)
    GenerateFiles(sys.argv[1])
    sys.exit(0)
