#!/usr/bin/python3 -Bsu

## Copyright (C) 2025 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

"""
build-config-file: Wrapper around config_builder's build_config_file with
safety checks. Builds a configuration directory into a config file.
"""

import sys
import os
import traceback
from pathlib import Path
from typing import NoReturn
from config_builder.config_builder import build_config_file


def print_usage() -> None:
    """
    Prints application syntax.
    """

    print(
        "Usage: build-config-file <config_dir> <output_file>", file=sys.stderr
    )


def main() -> NoReturn:
    """
    Main application function.
    """

    if len(sys.argv) != 3:
        print_usage()
        sys.exit(1)

    config_dir: Path = Path(sys.argv[1])
    output_file: Path = Path(sys.argv[2])

    if not config_dir.is_dir():
        print(
            f"Specified configuration directory '{config_dir}' is not a "
            "directory!",
            file=sys.stderr,
        )
        print_usage()
        sys.exit(1)

    if (
        not os.access(config_dir, os.R_OK)
        or not os.access(config_dir, os.X_OK)
    ):
        print(
            f"Cannot access configuration directory '{config_dir}'!",
            file=sys.stderr,
        )
        print_usage()
        sys.exit(1)

    for config_file in config_dir.iterdir():
        if not config_file.is_file():
            continue
        if not os.access(config_file, os.R_OK):
            print(
                f"Cannot access configuration file '{config_file}' in "
                f"configuration directory '{config_dir}'!",
                file=sys.stderr,
            )
            print_usage()
            sys.exit(1)

    if not output_file.is_file():
        if not os.access(output_file.parent, os.W_OK) or not os.access(
            output_file.parent, os.X_OK
        ):
            print(
                f"Cannot write new file '{output_file}' to directory "
                f"'{output_file.parent}'!",
                file=sys.stderr,
            )
            print_usage()
            sys.exit(1)
    else:
        if not os.access(output_file, os.W_OK):
            print(
                f"Cannot write to existing file '{output_file}'!",
                file=sys.stderr,
            )
            print_usage()
            sys.exit(1)

    try:
        build_config_file(config_dir, output_file)
    except Exception:
        print(
            f"Error encountered while building configuration file "
            f"'{output_file}' from directory '{config_dir}':",
            file=sys.stderr,
        )
        print(traceback.format_exc(), file=sys.stderr)
        sys.exit(1)

    sys.exit(0)


if __name__ == "__main__":
    main()
