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

import os
import shutil
from pathlib import Path
from subprocess import check_call

uname = Path("/tmp/.loguser")

with open(uname, "r", encoding="utf-8") as f:
    logname = f.readline()

keyfile = Path(f"/home/{logname}/.config/wire_py/pbwgk.pem")
dirname = Path("/tmp/tlecdcwg/")
PKEYFILE = "/usr/local/etc/ssl/pwgk.pem"

if not keyfile.is_file():

    check_call(
        [
            "openssl",
            "rsa",
            "-in",
            PKEYFILE,
            "-out",
            keyfile,
            "-outform",
            "PEM",
            "-pubout",
        ]
    )
    shutil.chown(keyfile, 1000, 1000)

    if dirname.exists():
        tl = os.listdir(f"{dirname}")
        CPTH = f"{keyfile}"
        CRYPTFILES = CPTH[:-9]

        if keyfile.exists() and len(tl) != 0:
            for tunnels in tl:
                sourcetl = f"{dirname}/{tunnels}"
                tlname = f"{CRYPTFILES}{tunnels[:-5]}.dat"
                check_call(
                    [
                        "openssl",
                        "pkeyutl",
                        "-encrypt",
                        "-inkey",
                        keyfile,
                        "-pubin",
                        "-in",
                        sourcetl,
                        "-out",
                        tlname,
                    ]
                )

else:

    if dirname.exists():
        tl = os.listdir(f"{dirname}")
        CPTH = f"{keyfile}"
        CRYPTFILES = CPTH[:-9]

        if keyfile.exists() and len(tl) != 0:
            for tunnels in tl:
                sourcetl = f"{dirname}/{tunnels}"
                tlname = f"{CRYPTFILES}{tunnels[:-5]}.dat"
                check_call(
                    [
                        "openssl",
                        "pkeyutl",
                        "-encrypt",
                        "-inkey",
                        keyfile,
                        "-pubin",
                        "-in",
                        sourcetl,
                        "-out",
                        tlname,
                    ]
                )