# -*- coding: utf-8 -*-

from setuphelpers import *

import psutil

bin_name = "wapttftpserver.exe"
service_name = "WaptTFTPServer"


def install():
    check_tftp_available()
    tftp_bin = os.path.join(WAPT.wapt_base_dir, bin_name)
    if service_installed(service_name):
        uninstall()
    killalltasks(bin_name)
    filecopyto(bin_name, tftp_bin)

    print("Apply WaptTFTPServer config")
    repo_path = inifile_readstring(WAPT.config_filename, "repo-sync", "local_repo_path") or makepath(WAPT.wapt_base_dir, "repository")
    tftp_path = makepath(repo_path, "wads", "pxe")
    mkdirs(tftp_path)
    server_conf_dir = makepath(WAPT.wapt_base_dir, "conf")
    server_ini = makepath(server_conf_dir, "waptserver.ini")
    mkdirs(server_conf_dir)
    inifile_writestring(server_ini, "tftpserver", "service_name", service_name)
    inifile_writestring(server_ini, "tftpserver", "root_dir", tftp_path)

    print("Add WaptTFTPServer firewall rule")
    run(f'netsh advfirewall firewall add rule name="{service_name}" dir=in action=allow program="{tftp_bin}" enable=yes')

    print("Create WaptTFTPServer service")
    if not service_installed(service_name):
        # run(rf'"{tftp_bin}" /install --service_name={service_name} --root_dir="{tftp_path}"')
        print(run(rf'"{tftp_bin}" --install'))
    if not service_is_running(service_name):
        service_start(service_name)
        
def audit():
    """
    Vérifie que tous les composants nécessaires pour WaptTFTPServer sont présents
    et correctement configurés.
    """
    errors = []

    # 1. Vérification du binaire principal
    tftp_bin = os.path.join(WAPT.wapt_base_dir, bin_name)
    if not isfile(tftp_bin):
        errors.append(f"Binaire manquant: {tftp_bin}")

    # 2. Vérification du répertoire de configuration
    server_conf_dir = makepath(WAPT.wapt_base_dir, "conf")
    if not isdir(server_conf_dir):
        errors.append(f"Répertoire de configuration manquant: {server_conf_dir}")

    # 3. Vérification du fichier de configuration
    server_ini = makepath(server_conf_dir, "waptserver.ini")
    if not isfile(server_ini):
        errors.append(f"Fichier de configuration manquant: {server_ini}")
    else:
        # Vérification des paramètres dans le fichier ini
        configured_service = inifile_readstring(server_ini, "tftpserver", "service_name")
        if not configured_service:
            errors.append(f"Paramètre 'service_name' manquant dans: {server_ini}")

        configured_root = inifile_readstring(server_ini, "tftpserver", "root_dir")
        if not configured_root:
            errors.append(f"Paramètre 'root_dir' manquant dans: {server_ini}")
        elif not isdir(configured_root):
            errors.append(f"Répertoire TFTP root manquant: {configured_root}")

    # 4. Vérification du répertoire TFTP
    repo_path = inifile_readstring(WAPT.config_filename, "repo-sync", "local_repo_path") or makepath(WAPT.wapt_base_dir, "repository")
    tftp_path = makepath(repo_path, "wads", "pxe")
    if not isdir(tftp_path):
        errors.append(f"Répertoire TFTP manquant: {tftp_path}")

    # 5. Vérification du service Windows
    if not service_installed(service_name):
        errors.append(f"Service Windows non installé: {service_name}")
    elif not service_is_running(service_name):
        errors.append(f"Service Windows non démarré: {service_name}")

    # Retour du résultat
    if errors:
        error_msg = "Erreurs détectées:\n" + "\n".join(f"  - {err}" for err in errors)
        print(error_msg)
        return "ERROR"
    else:
        return "OK"

def uninstall():
    tftp_bin = os.path.join(WAPT.wapt_base_dir, bin_name)
    server_conf_dir = makepath(WAPT.wapt_base_dir, "conf")

    print("Remove WaptTFTPServer service")
    if service_installed(service_name):
        if service_is_running(service_name):
            service_stop(service_name)
        print(run(rf'"{tftp_bin}" --uninstall'))

    print("Remove WaptTFTPServer firewall rule")
    run(f'netsh advfirewall firewall delete rule name="{service_name}" program="{tftp_bin}"')

    remove_file(tftp_bin)
    if len(glob.glob(server_conf_dir + os.sep + "*")) <= 1:
        remove_tree(server_conf_dir)

def check_tftp_available():
    for conn in psutil.net_connections(kind='udp'):
        if conn.laddr and conn.laddr.port == 69:
            local_addr = f"{conn.laddr.ip}:{conn.laddr.port}"
            pid = conn.pid
            exe_name = "unknown"

            if pid:
                try:
                    proc = psutil.Process(pid)
                    exe_name = proc.name()
                except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                    pass

            if exe_name != "wapttftpserver.exe":
                error(f"port 69 already being listened to by {exe_name}")