import fcntl
import logging
import os
import sys
import urllib.request
from typing import NoReturn

startup_logger = logging.getLogger("startup")
logger = logging.getLogger(__name__)
LOCKFILE = "/run/lock/tomte.lock"

TEST_URLS = [
    "https://tuxedocomputers.com/",  # TUXEDO
    "https://deb.debian.org/",  # Debian
    "https://kernel.org/",  # kernel.org
    "https://1.1.1.1/",  # Cloudflare (DNS + CDN)
    "https://8.8.8.8/",  # Google DNS
]


def tomte_exit(code: int) -> NoReturn:
    startup_logger.info("Exited tomte with code: " + str(code))
    sys.exit(code)


def check_internet(timeout: int = 3) -> None:
    if os.environ.get("TUXEDO_TOMTE_SKIP_FATALS") == "1":
        logger.warning(
            "Skipping fatal startup checks because TUXEDO_TOMTE_LIGHT_SKIP_FATALS=1"
        )
        return

    for url in TEST_URLS:
        try:
            urllib.request.urlopen(url, timeout=timeout)
            return
        except Exception:
            continue

    logger.critical("No network connection found.")
    tomte_exit(1)


def check_single_instance_lock() -> None:
    if os.environ.get("TUXEDO_TOMTE_SKIP_FATALS") == "1":
        logger.warning(
            "Skipping fatal startup checks because TUXEDO_TOMTE_LIGHT_SKIP_FATALS=1"
        )
        return

    lock_fd = os.open(LOCKFILE, os.O_RDWR | os.O_CREAT, 0o600)
    try:
        fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        logger.critical("Another instance of TUXEDO Tomte is already running.")
        tomte_exit(1)


def check_root_privileges() -> None:
    if os.environ.get("TUXEDO_TOMTE_SKIP_FATALS") == "1":
        logger.warning(
            "Skipping fatal startup checks because TUXEDO_TOMTE_LIGHT_SKIP_FATALS=1"
        )
        return

    if os.geteuid() != 0:
        logger.critical(
            "No root priviliges detected. Please execute with `sudo` or as root."
        )
        tomte_exit(1)
