import os
import time
import pwd

STATE_FILE = "/home/crime5/.timer/timer_state.txt"
END_STATE = "/home/crime5/.timer/end_state.txt"


def drop_privileges(user):
    pw = pwd.getpwnam(user)
    os.setgid(pw.pw_gid)
    os.setuid(pw.pw_uid)


def countdown(seconds):
    if os.path.exists(END_STATE):
        os.remove(END_STATE)

    for remaining in range(seconds, 0, -1):
        with open(STATE_FILE, "w") as f:
            f.write(str(remaining))

        mins, secs = divmod(remaining, 60)
        with open("/home/crime5/timer.txt", "w") as f:
            f.write(f"{mins:02d}:{secs:02d}")

        time.sleep(1)

    if os.path.exists(STATE_FILE):
        os.remove(STATE_FILE)

    with open(END_STATE, "w") as f:
        f.write("timeout")

    print("Du hast verloren – der Timer ist abgelaufen!")


if __name__ == "__main__":
    drop_privileges("crime5")
    countdown(600)
