from flask import Flask, render_template, request, jsonify, url_for
import subprocess
import re
import time

app = Flask(__name__)

# Hier maak je een lijst van VM-taken die aan de gang zijn.
vm_status = {}

def get_network_bridges():
    try:
        result = subprocess.run(['brctl', 'show'], capture_output=True, text=True, check=True)
        bridges = []
        for line in result.stdout.splitlines():
            parts = line.split()
            if len(parts) > 0 and not parts[0].startswith(("fwbr", "tap", "enp", "fwpr", "bridge")):
                bridges.append(parts[0])
        return bridges
    except subprocess.CalledProcessError as e:
        print(f"Fout bij het ophalen van netwerkbridges: {e}")
        return []

def get_storage_types():
    try:
        result = subprocess.run(['pvesm', 'status'], capture_output=True, text=True, check=True)
        storage_types = []
        for line in result.stdout.splitlines()[1:]:
            parts = line.split()
            if parts:
                storage_types.append(parts[0])
        return storage_types
    except subprocess.CalledProcessError as e:
        print(f"Fout bij het ophalen van storage types: {e}")
        return []

def get_ip_addresses_from_output(output):
    # Zoek naar zowel IPv4 als IPv6 adressen van eth0 in de output
    ipv4_addresses = re.findall(r'eth0 - ipv4: (\d+\.\d+\.\d+\.\d+)', output)  # Voor IPv4 adressen
    ipv6_addresses = re.findall(r'eth0 - ipv6: ([a-f0-9:]+)', output)  # Voor IPv6 adressen

    # Combineer beide lijsten van adressen
    return ipv4_addresses + ipv6_addresses

@app.route('/', methods=['GET'])
def index():
    bridges = get_network_bridges()
    storage_types = get_storage_types()
    return render_template('index.html', bridges=bridges, storage_types=storage_types)

@app.route('/check_vm_status/<vmnaam>', methods=['GET'])
def check_vm_status(vmnaam):
    status = vm_status.get(vmnaam, 'running')  # Zet de status op 'running' als deze er nog niet is
    return jsonify({'status': status})

@app.route('/create_vm', methods=['POST'])
def create_vm():
    try:
        vmnaam = request.form['vmnaam']
        
        vm_status[vmnaam] = 'running'
        
        vmgebruiker = request.form['vmgebruiker']
        vmwachtwoord = request.form['vmwachtwoord']
        ssh_key = request.form.get('ssh_key', '')
        vmdisk_size = request.form['vmdisk_size']
        network_bridge = request.form['network_bridge']
        ram = request.form['ram']
        vm_cores = request.form['vm_cores']
        storage = request.form['storage']
        os = request.form['os']
        
        command = [
            './create.sh',
            '-n', vmnaam,
            '-u', vmgebruiker,
            '-p', vmwachtwoord,
            '-k', ssh_key,
            '-d', vmdisk_size,
            '-b', network_bridge,
            '-m', ram,
            '-c', vm_cores,
            '-s', storage,
            '-o', os,
            '-t', 'y'
        ]
        
       # Voer het create.sh script uit en vang de output op
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        
        vm_status[vmnaam] = 'completed'
        
        # Verwerk de output van het script en zoek naar IP-adressen
        ip_addresses = get_ip_addresses_from_output(result.stdout)

        return jsonify({"success": True, "ip_addresses": ip_addresses})
    except Exception as e:
        print(f"Fout bij het aanmaken van de VM: {e}")
        return jsonify({"success": False, "error": str(e)})
        
        vm_status[vmnaam] = 'failed'
        return jsonify({'success': False, 'error': str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
