#!/usr/bin/env python3
import os
import sys
import time
import math
import subprocess
import shutil

def check_root():
    if os.geteuid() != 0:
        print("\033[1;31m[!] ERREUR : Tu dois lancer mdeh4x avec sudo !\033[0m")
        print("\033[1;33mW: Use sudo to use this tool and mdeh4x is installed in ~/.local/bin if you wanna use it in sudo or everywhere, Use sudo ~/.local/bin/mdeh4x install. THANKS :)\033[0m")
        print("\033[1;33mW: It doesn't have auto service detection to enable it in persistence yet, but stay tuned i will work on it. Use the start command after every reboot.\033[0m")
        sys.exit(1)

def get_hardware_specs():
    ram_kb = 0
    with open('/proc/meminfo', 'r') as f:
        for line in f:
            if 'MemTotal' in line:
                ram_kb = int(line.split()[1])
                break
    ram_gb = math.ceil(ram_kb / (1024**2))
    cores = os.cpu_count() or 2
    return ram_gb, cores

def calculate_optimal_settings(ram_gb, cores):
    if ram_gb <= 4:
        zram_size = f"{ram_gb * 2}G"
    elif ram_gb <= 16:
        zram_size = f"{int(ram_gb * 1.5)}G"
    elif ram_gb >= 1024:
        zram_size = "1024G"
    else:
        zram_size = f"{ram_gb}G"

    if cores <= 2:
        zstd_level = 3
    elif cores <= 4:
        zstd_level = 3
    else:
        zstd_level = 3

    return zram_size, zstd_level

def animate_h4x(msg, color_code):
    print(f"\n{color_code}[ MDEH4X ] {msg}\033[0m\n")
    frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
    for i in range(1, 101):
        frame = frames[i % 10]
        bar = '#' * (i // 5)
        sys.stdout.write(f"\r\033[1;36m{frame}\033[0m {color_code}▶︎•|I||||I|I||IIII||||||III|\033[0m [{bar:<20}] {i}% ")
        sys.stdout.flush()
        time.sleep(0.05)
    print(f"\n\n{color_code}[ OK ] Séquence terminée.\033[0m\n")

def run_cmd(cmd):
    subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

def start_system():
    ram_gb, cores = get_hardware_specs()
    zram_size, zstd_level = calculate_optimal_settings(ram_gb, cores)

    print(f"\033[1;34m[ MDEH4X ] HARDWARE DETECTED : {ram_gb}GB RAM | {cores} CPU CORES\033[0m")
    print(f"\033[1;33m[ MDEH4X ] OPTIMAL CONFIG CALCULATED : ZRAM {zram_size} | ZSTD LEVEL {zstd_level}\033[0m")
    
    animate_h4x("INJECTION DES PROTOCOLES DE SURCADENÇAGE...", "\033[1;32m")

    run_cmd("sysctl -w vm.swappiness=180")
    run_cmd("sysctl -w vm.vfs_cache_pressure=20")
    run_cmd("sysctl -w vm.dirty_background_ratio=3")
    run_cmd("sysctl -w vm.dirty_ratio=6")

    run_cmd("modprobe zram")
    run_cmd("swapoff /dev/zram0")
    run_cmd("echo 1 > /sys/block/zram0/reset")
    run_cmd(f'echo "algo=zstd level={zstd_level}" > /sys/block/zram0/comp_algorithm || echo zstd > /sys/block/zram0/comp_algorithm')
    run_cmd(f"echo {zram_size} > /sys/block/zram0/disksize")
    run_cmd("mkswap /dev/zram0")
    run_cmd("swapon -p 100 /dev/zram0")

    if not os.path.exists('/swapfile'):
        run_cmd("dd if=/dev/zero of=/swapfile bs=1M count=4096 status=none")
        run_cmd("chmod 600 /swapfile")
        run_cmd("mkswap /swapfile")
    run_cmd("swapon -p 5 /swapfile")
    run_cmd("swapon -p -2 /dev/mmcblk0p2")

    print("\033[1;32m[ MDEH4X ] PERFORMANCES MAXIMALES ACTIVÉES.\033[0m")
    print("-" * 48)
    os.system("zramctl")
    os.system("swapon --show")
    os.system("free -h")

def stop_system():
    animate_h4x("PURGE DES SYSTÈMES ET RETOUR AUX PARAMÈTRES D'USINE...", "\033[1;35m")
    
    run_cmd("sysctl -w vm.swappiness=60")
    run_cmd("sysctl -w vm.vfs_cache_pressure=100")
    run_cmd("sysctl -w vm.dirty_background_ratio=10")
    run_cmd("sysctl -w vm.dirty_ratio=20")
    
    run_cmd("swapoff /dev/zram0")
    run_cmd("echo 1 > /sys/block/zram0/reset")
    run_cmd("swapoff /swapfile")
    run_cmd("swapon -p -2 /dev/mmcblk0p2")

    print("\033[1;35m[ MDEH4X ] MODE NORMAL RESTAURÉ. SYSTÈME STABILISÉ.\033[0m")
    print("-" * 48)
    os.system("swapon --show")
    os.system("free -h")

def install_global():
    print("\033[1;36m[ MDEH4X ] INJECTION FORCEE DANS LE NOYAU SUDO...\033[0m")
    current_path = os.path.abspath(sys.argv[0])
    
    # On force la COPIE PHYSIQUE, pas de symlink capricieux
    run_cmd(f"cp -f {current_path} /usr/bin/mdeh4x")
    run_cmd(f"cp -f {current_path} /usr/sbin/mdeh4x")
    run_cmd(f"cp -f {current_path} /usr/local/bin/mdeh4x")
    
    # On donne les droits d'exécution partout
    run_cmd("chmod +x /usr/bin/mdeh4x /usr/sbin/mdeh4x /usr/local/bin/mdeh4x")
            
    print("\033[1;32m[ OK ] Exécutables copiés avec succès dans /usr/bin et /usr/sbin !\033[0m")
    print("\033[1;33m[!] Tu peux maintenant taper de n'importe où : sudo mdeh4x start\033[0m")

def delete_system():
    print("\033[1;31m[ MDEH4X ] DÉSINSTALLATION GLOBALE EN COURS...\033[0m")
    stop_system()
    
    # Suppression des clones sudo
    run_cmd("rm -f /usr/bin/mdeh4x /usr/sbin/mdeh4x /usr/local/bin/mdeh4x")
        
    print("\033[1;32m[ OK ] Les ponts SUDO ont été détruits.\033[0m")
    print("\033[1;33m[!] Le fichier maitre de Python est toujours là. Pour le détruire aussi :\033[0m")
    print("\033[1;31m    sudo pip uninstall mdeh4x --break-system-packages\033[0m")

if __name__ == "__main__":
    check_root()
    if len(sys.argv) < 2:
        print("\033[1;37mUtilisation : sudo mdeh4x {start|stop|install|del}\033[0m")
        sys.exit(1)
        
    cmd = sys.argv[1].lower()
    if cmd == "start":
        start_system()
    elif cmd == "stop":
        stop_system()
    elif cmd == "install":
        install_global()
    elif cmd == "del":
        delete_system()
    else:
        print("\033[1;37mUtilisation : sudo mdeh4x {start|stop|install|del}\033[0m")
