# SPDX-License-Identifier: MIT """The BIOS socket: bring your own Atari ROM, found by SHA-1 and read in place. Open decision 5: Atari's own BIOS only (the 4-port CO19156 or revision A CO19156A). Nothing is ever copied or written: zip archives are read through memory. Search order: an explicit path, ``$A5200_BIOS``, files and zips under ``~/.local/share/a5200-python/bios/``, then the ROM sets named by ``$NO_INTRO_DIR`` and ``$MAME_ROMPATH`` (docs/start-here.md "The BIOS"). """ from __future__ import annotations import hashlib import io import os import zipfile from pathlib import Path from .machine import BIOS_NAMES USER_PLACE = Path.home() / ".local/share/a5200-python/bios" def default_places() -> list[Path]: """The user folder, then the romsets named by the family's environment variables (``NO_INTRO_DIR``, ``MAME_ROMPATH``), each skipped when unset.""" places = [USER_PLACE] if os.environ.get("NO_INTRO_DIR"): places.append( Path(os.environ["NO_INTRO_DIR"]) / "Atari - Atari 5200" / "[BIOS] Atari 5200 (USA).zip" ) if os.environ.get("MAME_ROMPATH"): rompath = Path(os.environ["MAME_ROMPATH"]) places += [rompath / "a5200.zip", rompath / "a5200a.zip"] # merged or non-merged return places class BiosNotFound(FileNotFoundError): pass def _candidates(place: Path): if place.is_dir(): for child in sorted(place.iterdir()): yield from _candidates(child) return if not place.is_file() or place.stat().st_size > 4 * 1024 * 1024: return data = place.read_bytes() if data[:4] == b"PK\x03\x04": with zipfile.ZipFile(io.BytesIO(data)) as archive: for info in archive.infolist(): if info.file_size == 2048: yield f"{place} :: {info.filename}", archive.read(info) elif len(data) == 2048: yield str(place), data def find_bios(sha1: str, path: str | Path | None = None) -> tuple[bytes, str]: """(the 2K image, where it was found) for the BIOS with this SHA-1.""" places = [] if path is not None: places.append(Path(path)) if os.environ.get("A5200_BIOS"): places.append(Path(os.environ["A5200_BIOS"])) places.extend(default_places()) for place in places: for where, data in _candidates(place): if hashlib.sha1(data).hexdigest() == sha1: return data, where name = BIOS_NAMES.get(sha1, sha1) raise BiosNotFound( f"BIOS {name} (SHA-1 {sha1}) not found; put the 2K ROM (or a zip holding it) " f"in ~/.local/share/a5200-python/bios/, set A5200_BIOS, or set NO_INTRO_DIR / " f"MAME_ROMPATH to sets that hold it" )