#!/usr/bin/env python3
"""
Save JSON sources to files

Author: Arjen Balfoort
Date: 2026-02-22
"""

import sys
import json
import subprocess

# If set to True, no changes will be made
DEBUG = False


def run_command(command: list):
    """
    Run a command and print its output.
    The print is flushed to ensure that the output is immediately
    visible and can be used by the PackageManagerThread class.
    """
    print(f"Running command: {' '.join(command)}", flush=True)
    command = ["stdbuf", "-oL"] + command
    try:
        with subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            universal_newlines=True,
            bufsize=1,
        ) as process:
            for line in process.stdout:
                print(line.strip(), flush=True)
            process.wait()
            if process.returncode != 0:
                print(f"Error: Command failed with return code {process.returncode}", flush=True)
                sys.exit(1)
    except Exception as e:
        print(f"Error: {e}", flush=True)
        sys.exit(1)

def main():
    if len(sys.argv) != 2:
        print("Usage: python3 repositories_sudo.py <json_file>")
        sys.exit(1)

    json_file = sys.argv[1]

    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            json_data = json.load(f)

        for entry_data in json_data:
            print(f"Saving {entry_data['section']} to {entry_data['file']}")
            if not DEBUG:
                with open(entry_data['file'], 'w', encoding='utf-8') as f:
                    f.write(entry_data['section'])

        # Run apt-get update in a separate thread to prevent blocking
        run_command(["apt-get", "update"])

        print("JSON sources saved to files successfully.")
        sys.exit(0)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    # Start logging
    print("repositories_sudo.py started.")
    main()
