#!/usr/bin/env python3

import os
import subprocess
import sys

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 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, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

def get_language():
    lang = os.getenv('LANG')
    if lang.startswith('de'):
        return 'de'
    else:
        return 'en'

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

def copy_grub_cfg():
    src = "/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 os.path.exists(src):
        os.link(src, dst)

def copy_systemd_service():
    src = "/usr/share/tuxedo-reboot-into-grub/tuxedo-reboot-into-grub.service"
    dst = "/etc/systemd/system/tuxedo-reboot-into-grub.service"
    if os.path.exists(src):
        os.link(src, dst)

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

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"]:
        exit()
    else:
        exit()
else:
   lang = get_language()
   print(NEED_ROOT[lang])
   exit()
