#!/usr/bin/env python3

import json
import subprocess
import sys
import threading

def extract_acls(vmid_min, vmid_max, output_file, remove_acl=False, append=False):
    print("Fetching ACLs...")

    if not append:
        with open(output_file, "w") as f:
            f.write("")

    result = subprocess.run(
        ["pveum", "acl", "list", "--output-format=json"],
        capture_output=True,
        text=True
    )

    acls = json.loads(result.stdout)

    def process_acl(acl_entry):
        path = acl_entry["path"]
        role = acl_entry["roleid"]
        user = acl_entry["ugid"]

        if "/vms/" in path:
            vmid = int(path.split("/vms/")[1])
            if vmid_min <= vmid <= vmid_max:
                print(f"Processing VMID: {vmid} (Path: {path}, Role: {role}, User: {user})")

                with open(output_file, "a") as f:
                    f.write(f"{path} {user} {role}\n")

                if (remove_acl):
                    subprocess.run(["pveum", "acl", "delete", path, users, "--roles", roles])

    # Process each ACL in background
    threads = []
    for acl_entry in acls:
        thread = threading.Thread(target=process_acl, args=(acl_entry,))
        thread.start()
        threads.append(thread)

    # Wait for all threads to finish
    for thread in threads:
        thread.join()

    print(f"ACLs extracted and saved to {output_file}")


def main():
    if len(sys.argv) < 4:
        print("Usage: extract_acls.py <vmid_min> <vmid_max> <output_file> --remove --append")
        sys.exit(1)

    vmid_min = int(sys.argv[1])
    vmid_max = int(sys.argv[2])
    output_file = sys.argv[3]
    remove_acl = "--remove" in sys.argv
    append = "--append" in sys.argv

    extract_acls(vmid_min, vmid_max, output_file, remove_acl, append)


if __name__ == "__main__":
    main()