#!/usr/bin/env python3
"""
Verify (and optionally fix) BMS46 checksums.

Usage:
    python3 -I bms46_checksum.py <file.bin>            # verify
    python3 -I bms46_checksum.py <file.bin> --fix      # rewrite in place
    python3 -I bms46_checksum.py <file.bin> --unswap OUT.bin
                                     # write a 16-bit un-swapped copy

Accepts a 256 KB full dump or a 32 KB partial (calibration) dump
(partial byte 0 = ROM 0x8010). Byte-swapped files are detected and
refused: un-swap them first with --unswap.

Algorithm (from the boot ROM routine at 0x314A, table at 0x3D00 /
0x14200, CRC table at 0x3D20): CRC-16/ARC (reflected poly 0xA001,
init 0x0000, no final XOR), result stored big-endian. Each descriptor
gives a start address and a pointer P; the covered data ends at
*(u32*)P - 1 and the CRC word is stored at *(u32*)P. Records of the
same group chain one running CRC. See ../bin-layout.md#checksums.
"""
import sys
from pathlib import Path

FULL, PARTIAL, PARTIAL_BASE = 0x40000, 0x8000, 0x8010

TABLE = []
for i in range(256):
    c = i
    for _ in range(8):
        c = (c >> 1) ^ 0xA001 if c & 1 else c >> 1
    TABLE.append(c)


def crc16_arc(data, crc=0):
    for b in data:
        crc = (crc >> 8) ^ TABLE[(crc ^ b) & 0xFF]
    return crc


class Rom:
    """ROM-addressed view over a full or partial dump."""

    def __init__(self, buf):
        self.buf = buf
        self.base = PARTIAL_BASE if len(buf) == PARTIAL else 0

    def has(self, a, n=1):
        return self.base <= a and a + n <= self.base + len(self.buf)

    def get(self, a, n):
        return bytes(self.buf[a - self.base:a - self.base + n])

    def u32(self, a):
        return int.from_bytes(self.get(a, 4), "big")

    def u16(self, a):
        return int.from_bytes(self.get(a, 2), "big")

    def put16(self, a, v):
        self.buf[a - self.base:a - self.base + 2] = v.to_bytes(2, "big")


def groups(rom):
    """CRC groups as [(name, [(start, end_incl)], crc_addr)]."""
    out = []
    # Boot (0x0000-0x3FFF): only if the dump contains a populated boot sector.
    if rom.has(0x3F42, 4) and rom.get(0, 4) != b"\xff\xff\xff\xff":
        p = rom.u32(0x3F42)
        out.append(("boot", [(0x0000, p - 1)], p))
    # Program: descriptor table at 0x14200 (ids 1+2, group 1).
    if rom.has(0x14200, 0x40) and rom.get(0x10000, 4) != b"\xff\xff\xff\xff":
        ranges, crc_at = [], None
        o = 0x14200
        while rom.get(o, 1) != b"\xff":
            gid, start, end, ptr = rom.get(o + 1, 1)[0], rom.u32(o + 4), rom.u32(o + 8), rom.u32(o + 12)
            if gid == 1:
                v = rom.u32(ptr)
                ranges.append((start, min(v - 1, end)))
                crc_at = v
            o += 16
        if ranges:
            out.append(("program", ranges, crc_at))
    # Calibration: 0x8040 .. *(0xFFF6)-1, CRC at *(0xFFF6) (= 0xFFFA).
    if rom.has(0x8040) and rom.has(0xFFF6, 4):
        p = rom.u32(0xFFF6)
        if not (0x8040 < p <= 0xFFFA):
            # Every known F000 cal stores 0x0000FFFA here. A blank/odd
            # trailer means the file was truncated or edited; don't guess.
            raise SystemExit(
                "calibration trailer invalid: end pointer @0xFFF6 = 0x%08X (expected 0x0000FFFA); "
                "trailer 0xFFF6-0xFFFF = %s" % (p, rom.get(0xFFF6, 10).hex(" ")))
        out.append(("calibration", [(0x8040, p - 1)], p))
    return out


def main():
    args = sys.argv[1:]
    if not args:
        raise SystemExit(__doc__)
    path = Path(args[0])
    buf = bytearray(path.read_bytes())
    if len(buf) not in (FULL, PARTIAL):
        raise SystemExit("expected 256 KB (full) or 32 KB (partial) dump, got %d bytes" % len(buf))
    if "--unswap" in args:
        dst = Path(args[args.index("--unswap") + 1])
        sw = bytearray(len(buf))
        sw[0::2], sw[1::2] = buf[1::2], buf[0::2]
        dst.write_bytes(sw)
        print("wrote un-swapped copy -> %s" % dst)
        return
    rom = Rom(buf)
    ident = rom.get(0x8010, 16)
    if ident[:8] == b"10117900":
        raise SystemExit("file is 16-bit byte-swapped (ident %r); run with --unswap first" % ident)
    print("ident: %s" % ident.decode("ascii", "replace"))
    fix = "--fix" in args
    bad = 0
    for name, ranges, at in groups(rom):
        c = 0
        for s, e in ranges:
            c = crc16_arc(rom.get(s, e - s + 1), c)
        stored = rom.u16(at)
        ok = c == stored
        span = " + ".join("0x%05X-0x%05X" % r for r in ranges)
        print("%-12s %s -> @0x%05X stored 0x%04X calc 0x%04X  %s"
              % (name, span, at, stored, c, "OK" if ok else ("FIXED" if fix else "MISMATCH")))
        if not ok:
            bad += 1
            if fix:
                rom.put16(at, c)
    if fix and bad:
        path.write_bytes(rom.buf)
        print("rewrote %d checksum(s) in %s" % (bad, path))
    sys.exit(0 if (fix or not bad) else 1)


if __name__ == "__main__":
    main()
