#!/usr/bin/env python3

import sys
import json
from pathlib import Path
import re
import subprocess

def generate_sops_config(repo_root):
    admin_keys = []

    # hardcode fingerprints because we can't really generate them automatically currently
    admin_keys.append("0C982F87B7AFBA0F504F90A2629E741947C87928") # clerie@clerie.de

    list_of_host_directories = sorted(list(filter(lambda path_object: path_object.is_dir(), (repo_root / "hosts").iterdir())))

    creation_rules = []

    for host_directory in list_of_host_directories:
        host_secrets_file = host_directory / "secrets.json"
        host_keys = []

        ssh_host_key_file = host_directory / "ssh.pub"

        if ssh_host_key_file.is_file():

            ssh_to_age_command = subprocess.run(["ssh-to-age", "-i", str(ssh_host_key_file)], capture_output=True, text=True)
            if ssh_to_age_command.returncode == 0:
                host_keys.append(ssh_to_age_command.stdout.strip())

        creation_rules.append({
            "key_groups": [{
                "age": host_keys,
                "pgp": admin_keys,
            }],
            "path_regex": re.escape(str(host_secrets_file)),
        })

    return {
        "creation_rules": creation_rules,
    }




if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("No repo root specified")
        exit(1)

    repo_root = Path(sys.argv[1])

    sops_config = generate_sops_config(repo_root)

    print(json.dumps(sops_config))