#!/usr/bin/python3
""" This Script encrypt Wireguardfiles for Wirepy users for more Security """

import argparse
import logging
from pathlib import Path
import pwd
import shutil
from subprocess import CompletedProcess, run
from shared_libs.wp_app_config import AppConfig
from shared_libs.common_tools import LogConfig

parser = argparse.ArgumentParser()
parser.add_argument("--user", required=True, help="Username of the target file system")
args = parser.parse_args()

LogConfig.logger(f"/home/{args.user}/.local/share/lxlogs/wirepy.log")
try:
    # Retrieve UID and GID
    user_info = pwd.getpwnam(args.user)
    uid = user_info.pw_uid  # User ID (e.g., 1000)
    gid = user_info.pw_gid  # Group ID (e.g., 1000)
except KeyError:
    logging.error(f"User '{args.user}' not found.", exc_info=True)
    exit(1)

keyfile: Path = Path(f"/home/{args.user}/.config/wire_py/pbwgk.pem")

target: Path = Path(f"/home/{args.user}/.config/wire_py/")

if not keyfile.is_file():

    process: CompletedProcess[str] = run(
        [
            "openssl",
            "rsa",
            "-in",
            AppConfig.SYSTEM_PATHS["pkey_path"],
            "-out",
            keyfile,
            "-outform",
            "PEM",
            "-pubout",
        ],
        capture_output=True,
        text=True,
        check=False,
    )

    # Output from Openssl Error
    if process.stderr:
        logging.error(f"{process.stderr} Code: {process.returncode}", exc_info=True)

    if process.returncode == 0:
        logging.info("Public key generated successfully.", exc_info=True)

    shutil.chown(keyfile, uid, gid)

# any() get True when directory is not empty
if AppConfig.TEMP_DIR.exists() and any(AppConfig.TEMP_DIR.iterdir()):
    clear_files = [str(file) for file in AppConfig.TEMP_DIR.glob("*.conf")]

    for config_file in clear_files:
        base_name = Path(config_file).stem
        process: CompletedProcess[str] = run(
            [
                "openssl",
                "pkeyutl",
                "-encrypt",
                "-inkey",
                keyfile,
                "-pubin",
                "-in",
                config_file,
                "-out",
                f"{target}/{base_name}.dat",
            ],
            capture_output=True,
            text=True,
            check=False,
        )

        # Output from Openssl Error
        if process.stderr:
            logging.error(process.stderr, exc_info=True)