# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2015-2016, 2026 InterGenJLU
"""Install-time Secure Boot state query for the Forge installer.

A lightweight, dependency-free read of the UEFI SecureBoot EFI variable,
used by the Confirm screen (D-2) to decide whether skipping MOK enrollment
needs an explicit no-boot acknowledgment.

The comprehensive POST-BOOT runtime verifier lives at
installer/tests/class2_runtime_sb_state.py (SecureBoot + SetupMode +
mokutil cross-check). This is the minimal INSTALL-TIME query, kept in the
backend so the production frontend never imports from the tests package
(which may not ship in the installed installer image). The GUID + binary
format are intentionally identical to the verifier's.

EFI variable binary format (/sys/firmware/efi/efivars/<Name>-<GUID>):
  bytes [0..3] — EFI_VARIABLE_ATTRIBUTES (uint32 LE)
  bytes [4..]  — raw payload (a single 0/1 byte for SecureBoot)
"""

from __future__ import annotations

from pathlib import Path
from typing import Optional

# EFI global-variable GUID for SecureBoot (UEFI spec) — matches
# installer/tests/class2_runtime_sb_state.py:EFI_GLOBAL_GUID.
_EFI_GLOBAL_GUID = "8be4df61-93ca-11d2-aa0d-00e098032b8c"
_EFIVARS_DIR = Path("/sys/firmware/efi/efivars")
# Present iff the host booted via UEFI (regardless of efivars readability).
_EFI_SYSFS_DIR = Path("/sys/firmware/efi")
_PAYLOAD_OFFSET = 4


def is_secure_boot_enabled(
    efivars_dir: Path = _EFIVARS_DIR,
) -> Optional[bool]:
    """Return the Secure Boot enforcement state.

    Returns:
        True  — SecureBoot EFI variable present and == 1 (enforcing).
        False — present and == 0 (off).
        None  — variable absent (non-EFI / no SB), unreadable (root
                required), or malformed.

    Callers MUST treat None as "unknown", NOT as "off". D-2 raises the
    MOK-skip warning only on a known-True so an unreadable/non-EFI host
    never shows a false (and trust-eroding) Secure-Boot warning.
    """
    path = efivars_dir / f"SecureBoot-{_EFI_GLOBAL_GUID}"
    try:
        raw = path.read_bytes()
    except (FileNotFoundError, PermissionError, OSError):
        return None
    if len(raw) <= _PAYLOAD_OFFSET:
        return None
    return raw[_PAYLOAD_OFFSET] == 1


def is_efi_firmware(efi_dir: Path = _EFI_SYSFS_DIR) -> bool:
    """True when the host booted via UEFI (the efi sysfs tree exists).

    Lets a caller distinguish is_secure_boot_enabled()'s two None cases:
      - None + is_efi_firmware()==False  -> BIOS / non-EFI: MOK is irrelevant,
        skipping is genuinely benign.
      - None + is_efi_firmware()==True   -> EFI host but the SecureBoot var
        was unreadable (non-root caller / broken efivarfs): SB *might* be
        enforcing, so a silent benign skip could still brick. The Confirm
        screen surfaces a softer informational note in this case (D-2
        hardening, IGOSC review 2026-05-29) without warning the BIOS majority.
    """
    return efi_dir.exists()
