"""Finding the BIOS: the user's retail dump read in place, or the free one, labelled. User decision 1 (docs/handoff-brief.md): the default is the retail BIOS, read in place from ``--bios``, then ``GBA_BIOS``, then the documented No-Intro set under ``GBA_NOINTRO_DIR``; Cult-of-GBA's free BIOS (MIT, fetched into ``reference/``) only when no dump is found, and every result says which ran. Nintendo's BIOS is never fetched, copied or committed: a ``.zip`` is read in memory. """ from __future__ import annotations import hashlib import os import zipfile from dataclasses import dataclass from pathlib import Path RETAIL_SHA1 = "300c20df6731a33952ded8c436f7f186d25d3492" GBP_SHA1 = "3d4b5d095576f5b994bf62c00cac9428a88b2b78" # the Game Boy Player's ("GameCube") NOINTRO_DIR = Path("/data/emu/source/myrient.erista.me/files/No-Intro") RETAIL_ZIP = "Nintendo - Game Boy Advance/[BIOS] Nintendo Game Boy Advance Boot ROM (World).zip" FREE_BIOS = Path(__file__).resolve().parents[2] / "reference/src/bios-cult-of-gba/bios.bin" SIZE = 0x4000 @dataclass(frozen=True) class BIOS: data: bytes source: str # where it was read from label: str # "retail", "gbp", "cult-of-gba" or "unknown" @property def is_retail(self) -> bool: return self.label == "retail" def _read(path: Path) -> bytes: if path.suffix.lower() == ".zip": with zipfile.ZipFile(path) as archive: name = next(n for n in archive.namelist() if not n.endswith("/")) return archive.read(name) return path.read_bytes() def _label(data: bytes, path: Path) -> str: sha1 = hashlib.sha1(data).hexdigest() if sha1 == RETAIL_SHA1: return "retail" if sha1 == GBP_SHA1: return "gbp" if path.resolve() == FREE_BIOS.resolve(): return "cult-of-gba" return "unknown" def load(path: str | Path) -> BIOS: path = Path(path).expanduser() data = _read(path) if len(data) != SIZE: raise ValueError(f"{path}: a GBA BIOS is {SIZE} bytes, not {len(data)}") return BIOS(data, str(path), _label(data, path)) def nointro_dir() -> Path: """The local No-Intro set: ``GBA_NOINTRO_DIR``, else the documented path.""" return Path(os.environ.get("GBA_NOINTRO_DIR", NOINTRO_DIR)) def find(explicit: str | Path | None = None, *, allow_free: bool = True) -> BIOS: """The BIOS to run: ``explicit``, else ``GBA_BIOS``, else the No-Intro retail dump, else (if allowed) the free BIOS.""" if explicit is not None: return load(explicit) if os.environ.get("GBA_BIOS"): return load(os.environ["GBA_BIOS"]) retail = nointro_dir() / RETAIL_ZIP if retail.exists(): return load(retail) if allow_free and FREE_BIOS.exists(): return load(FREE_BIOS) raise FileNotFoundError( "no GBA BIOS: pass --bios, set GBA_BIOS or GBA_NOINTRO_DIR, or fetch the free one " "with scripts/fetch_references.py" )