#!/usr/bin/env python3

import os
import signal
import subprocess
import sys
from pathlib import Path
from typing import Any, NoReturn

CLEAR_SCREEN = ["clear"]
DAEMON_RELOAD = ["systemctl", "daemon-reload"]
ENABLE_SERVICE = ["systemctl", "enable", "tuxedo-reboot-into-grub.service"]
REBOOT = ["systemctl", "reboot"]
UPDATE_GRUB = ["grub-mkconfig", "-o", "/boot/grub/grub.cfg", "&>", "/dev/null"]

QUERY = {
    "en": "Do you want to reboot NOW? Please make sure to safe all work.\nType 'y'/'yes' to continue or 'n'/'no' to abort\nPress Enter to confirm\n",
    "de": "Möchten Sie JETZT neu starten? Bitte stellen Sie sicher, dass Sie alle Arbeiten gespeichert haben.\nGeben Sie 'j'/'ja' ein, um fortzufahren, oder 'n'/'nein', um den Vorgang abzubrechen.\nEnter drücken zum bestätigen\n",
}
NEED_ROOT = {
    "en": "This program needs to be run as root user!",
    "de": "Dieses Programm muss als Root-Benutzer ausgeführt werden!",
}


def sigint_handler(_signal: Any, _frame: Any) -> NoReturn:  # noqa: ANN401  # pyright: ignore[reportExplicitAny]
    print()
    sys.exit(0)


def run_subprocess(cmd: list[str]) -> None:
    subprocess.run(cmd, check=True, text=None, capture_output=False)


def run_subprocess_devnull(cmd: list[str]) -> None:
    subprocess.run(
        cmd,
        check=False,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )


def get_language() -> str:
    lang = os.getenv("LANG")
    if lang is not None and lang.startswith("de"):
        return "de"
    return "en"


def print_help() -> None:
    lang = get_language()
    help_file = Path(f"/usr/share/tuxedo-reboot-into-grub/help/help.{lang}")
    try:
        with help_file.open(encoding="utf-8") as f:
            print(f.read())
    except FileNotFoundError:
        sys.exit(1)


def copy_grub_cfg() -> None:
    src = Path("/usr/share/tuxedo-reboot-into-grub/99-tuxedo-reboot-into-grub-tmp.cfg")
    dst = "/etc/default/grub.d/99-tuxedo-reboot-into-grub-tmp.cfg"
    if src.exists():
        src.symlink_to(dst)


def copy_systemd_service() -> None:
    src = Path("/usr/share/tuxedo-reboot-into-grub/tuxedo-reboot-into-grub.service")
    dst = "/etc/systemd/system/tuxedo-reboot-into-grub.service"
    if src.exists():
        src.symlink_to(dst)


if __name__ == "__main__":
    if "--help" in sys.argv or "-h" in sys.argv:
        print_help()
        sys.exit(0)

signal.signal(signal.SIGINT, sigint_handler)

if os.geteuid() == 0:
    lang = get_language()
    answer = input(QUERY[lang])
    if answer in ["y", "yes", "j", "ja"]:
        run_subprocess(CLEAR_SCREEN)
        copy_grub_cfg()
        copy_systemd_service()
        run_subprocess(DAEMON_RELOAD)
        run_subprocess_devnull(ENABLE_SERVICE)
        run_subprocess_devnull(UPDATE_GRUB)
        run_subprocess(REBOOT)
    elif answer in ["n", "no", "nein"]:
        sys.exit()
    else:
        sys.exit()
else:
    lang = get_language()
    print(NEED_ROOT[lang])
    sys.exit()
