#! /usr/bin/env python3.11

import os, stat

def create_folder (check_folders = list):
    exist_dict = []
    for folder in check_folders:
        if os.path.isdir(folder) is True:
            exist_dict.append({"name": folder, "status": "existiert bereits"})
        else:
            os.makedirs(folder, exist_ok=True)
            exist_dict.append({"name": folder, "status": "wurde angelegt"})
    return exist_dict

def read_sshkeys(ssh_folder = str):
    key_liste = []
    for root, dirs, files in os.walk(ssh_folder, topdown=False):
        for name in files: 
            FullPATH = str(os.path.join(root, name))
            if FullPATH.endswith(".pub") is False and FullPATH.endswith("known_hosts") is False and FullPATH.endswith("authorized_keys") is False:
                key_liste.append(FullPATH)
    return key_liste


def create_scripts_addkeys(script_folder = str, keys = list):
    try:
        script_file = script_folder + "/ssh-add.sh"
        with open(file=script_file, mode="w") as script: 
            print("""#! /bin/bash\nsleep 10\nSSH_ASKPASS=/usr/bin/ksshaskpass\nexport SSH_ASKPASS\nssh-add {ssh_keys}
                """.format(ssh_keys=" ".join(keys)), file=script)

        os.chmod(path=script_file, mode=stat.S_IRWXU)
    except: 
        raise PermissionError("Keine Rechte die Datei " + script_file + " zu erstellen")
    else:
        return print(script_file, "erstellt",sep=" ")

def create_scripts_shutdown(script_folder = str):
    try:
        script_file = script_folder + "/ssh-agent-shutdown.sh"
        with open(file=script_file, mode="w" ) as script: 
            print("""#!/bin/sh\n[ -z "$SSH_AGENT_PID" ] || eval "$(ssh-agent -k)" """, file=script)  
        os.chmod(path=script_file, mode=stat.S_IRWXU) 
    except:
        raise PermissionError("Keine Rechte die Datei " + script_file + " zu erstellen")
    else:
        return print(script_file, "erstellt",sep=" ")

def create_scripts_startup(script_folder = str):
    try:
        script_file = script_folder + "/ssh-agent-shartup.sh"
        with open(file=script_file, mode="w" ) as script: 
            print("""#!/bin/sh\n[ -n "$SSH_AGENT_PID" ] || eval "$(ssh-agent -s)"\nSSH_ASKPASS=/usr/bin/ksshaskpass\nexport SSH_ASKPASS""", file=script)  
        os.chmod(path=script_file, mode=stat.S_IRWXU) 
    except:
        raise PermissionError("Keine Rechte die Datei " + script_file + " zu erstellen")
    else:
        return print(script_file, "erstellt",sep=" ")

def set_key_permission(key_liste = list):
    exist_dict = []
    for file in key_liste:
        status_file = str(oct(os.stat(file).st_mode)[-3:])
        if status_file != "600":
            os.chmod(path=file, mode=0o600)
            exist_dict.append({"file": file, "status": "berechtigung geändert"})
        else:
            exist_dict.append({"file": file, "status": "berechtigung sind richtig"})
    return exist_dict
        
######
def main(): 
    kde_folders = [
        os.environ["HOME"] + "/.config/autostart-scripts", 
        os.environ["HOME"] + "/.config/plasma-workspace/shutdown",
        os.environ["HOME"] + "/.config/plasma-workspace/env"
    ]

    for test in create_folder(check_folders=kde_folders):
        print("Folder:" + test["name"] + " status: " + test["status"])

    for permission in set_key_permission(read_sshkeys(os.environ["HOME"] + "/.ssh")):
        print("file: " + permission["file"] + " status: " + permission["status"])

    create_ssh_script_addkey = create_scripts_addkeys(kde_folders[0], read_sshkeys(os.environ["HOME"] + "/.ssh") )
    create_ssh_script_shutdown = create_scripts_shutdown(script_folder=kde_folders[1])
    create_ssh_script_startup = create_scripts_startup(script_folder=kde_folders[2])

main()
