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

Usage:
    python3 -I ms43_checksum.py <file.bin>            # verify
    python3 -I ms43_checksum.py <file.bin> --fix      # rewrite in place
    python3 -I ms43_checksum.py <file.bin> --json     # machine-readable report

Accepts a 512 KB full image (file offset == flash offset) or a 64 KB
calibration file (file offset 0 == flash offset 0x70000, ECU 0x70000).

Six checksums (the first five ported from nfsx packages/flash-data/src/ms4x-checksum.ts,
which follows the MS4x community documentation):

  Boot           CRC-16  result u16 @ 0x03C24, range @ 0x03C28, seed u16 @ 0x03FE6
  Program        CRC-16  result u16 @ 0x6FDE0, count + region table inline,
                         seed pointer @ 0x6ED42
  Calibration    CRC-16  result u16 @ 0x73FE0, count + region table inline,
                         seed pointer @ 0x6ED9A (empty -> seed @ 0x7000C)
  Program (add)  add-32  result u32 @ 0x6FDAE, init @ 0x6FDB2, 2 regions @ 0x6FDBE
  Calibration (add) add-32 result u32 @ 0x72FFC, init @ 0x6FDB8, 2 regions @ 0x6FDCE
  Boot block (add) add-32 result u32 @ 0x0BFF8, init 0, over 0x08000-0x0BFF7
                   (not in nfsx; found by this wiki, matches every dump)

CRC-16: reflected polynomial 0xA001 (CRC-16/ARC table), init = seed read
from the image, no final XOR, stored little-endian. Chained over all
regions (inclusive ends). add-32: initial u32 + sum of u16 LE words over
[start, end) of each region, mod 2^32.

Region addresses are ECU bus addresses; upper word 0x9..0xE maps to file
0x1..0x6 (file = ECU - 0x80000), 0x7 maps 1:1.

--fix order: add-32 first (the calibration add-32 result at 0x72FFC lies
inside the calibration CRC range), then the CRC-16s.

A 64 KB file holds only the calibration. Its CRC is fully self-described.
The calibration add-32 region table lives in the program (0x6FDCE), so for
64 KB files it is taken from a built-in table keyed on the SW number in the
calibration ident (verified for 430066 and 430069 only).
"""
import json
import sys
from pathlib import Path

FULL, CAL = 0x80000, 0x10000
CAL_BASE = 0x70000

# Calibration add-32 regions (file offsets, end exclusive), read from 0x6FDCE
# of the full images of each SW. Used only for 64 KB calibration files.
CAL_ADD32_REGIONS = {
    "430066": [(0x712CC, 0x7131C), (0x7EB94, 0x7EE16)],
    "430069": [(0x712C6, 0x71316), (0x7EB94, 0x7EE16)],
}
CAL_ADD32_INIT = 0xA5A5A5A5  # u32 @ 0x6FDB8 in every known full image

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(buf, start, end, crc):
    """CRC over buf[start..end] inclusive."""
    for b in buf[start:end + 1]:
        crc = (crc >> 8) ^ TABLE[(crc ^ b) & 0xFF]
    return crc & 0xFFFF


def add32(buf, start, end, acc):
    """Sum u16 LE words over buf[start..end) into acc."""
    for p in range(start, end - 1, 2):
        acc = (acc + (buf[p] | buf[p + 1] << 8)) & 0xFFFFFFFF
    return acc


def u16(buf, o):
    return buf[o] | buf[o + 1] << 8


def u32(buf, o):
    return u16(buf, o) | u16(buf, o + 2) << 16


def put16(buf, o, v):
    buf[o:o + 2] = v.to_bytes(2, "little")


def put32(buf, o, v):
    buf[o:o + 4] = v.to_bytes(4, "little")


def ecu_to_file(lo, hi):
    """(lo, hi) u16 pair holding an ECU address -> file offset."""
    if 0x9 <= hi <= 0xE:
        hi -= 0x8
    return hi << 16 | lo


def addr_at(buf, o):
    return ecu_to_file(u16(buf, o), u16(buf, o + 2))


# -- individual checksums (all work on a 512 KB file-offset buffer) -------

def boot(buf):
    start, end = addr_at(buf, 0x3C28), addr_at(buf, 0x3C2C)
    seed = u16(buf, 0x3FE6)
    return dict(name="Boot", kind="crc16", at=0x3C24, size=2,
                stored=u16(buf, 0x3C24), computed=crc16(buf, start, end, seed),
                seed=seed, ranges=[(start, end)])


def inline_crc(buf, name, at, seed_ptr, fallback):
    lo, hi = u16(buf, seed_ptr), u16(buf, seed_ptr + 2)
    if lo == 0xFFFF and hi == 0xFFFF:
        if fallback is None:
            raise ValueError(f"{name}: seed pointer @0x{seed_ptr:X} empty")
        seed_addr = fallback
    else:
        seed_addr = ecu_to_file(lo, hi)
    seed = u16(buf, seed_addr)
    count = u16(buf, at + 2)
    if not 0 < count < 16:
        raise ValueError(f"{name}: implausible region count {count} @0x{at + 2:X}")
    crc, ranges = seed, []
    for i in range(count):
        e = at + 4 + 8 * i
        s, t = addr_at(buf, e), addr_at(buf, e + 4)
        ranges.append((s, t))
        crc = crc16(buf, s, t, crc)
    return dict(name=name, kind="crc16", at=at, size=2, stored=u16(buf, at),
                computed=crc, seed=seed, seed_addr=seed_addr, ranges=ranges)


def program(buf):
    return inline_crc(buf, "Program", 0x6FDE0, 0x6ED42, None)


def calibration(buf):
    return inline_crc(buf, "Calibration", 0x73FE0, 0x6ED9A, 0x7000C)


def add_sum(buf, name, at, init, ranges):
    acc = init
    for s, t in ranges:
        acc = add32(buf, s, t, acc)
    return dict(name=name, kind="add32", at=at, size=4, stored=u32(buf, at),
                computed=acc, init=init, ranges=ranges)


def table_ranges(buf, o):
    return [(addr_at(buf, o + 8 * i), addr_at(buf, o + 8 * i + 4)) for i in range(2)]


def boot_block_add(buf):
    """Second boot block (32 KB sector @ 0x8000): plain u16 word sum."""
    return add_sum(buf, "Boot block (add)", 0xBFF8, 0, [(0x8000, 0xBFF8)])


def program_add(buf):
    return add_sum(buf, "Program (add)", 0x6FDAE, u32(buf, 0x6FDB2), table_ranges(buf, 0x6FDBE))


def calibration_add(buf, sw=None):
    if sw is None:
        return add_sum(buf, "Calibration (add)", 0x72FFC, u32(buf, 0x6FDB8),
                       table_ranges(buf, 0x6FDCE))
    return add_sum(buf, "Calibration (add)", 0x72FFC, CAL_ADD32_INIT, CAL_ADD32_REGIONS[sw])


# -- driver ----------------------------------------------------------------

def cal_sw(buf):
    """SW number from the calibration ident at 0x70008 ('4300xx')."""
    s = bytes(buf[0x70008:0x7000E])
    return s.decode("ascii", "replace")


def load(path):
    raw = bytearray(Path(path).read_bytes())
    if len(raw) == FULL:
        return raw, raw, False
    if len(raw) == CAL:
        full = bytearray(b"\xFF" * FULL)
        full[CAL_BASE:CAL_BASE + CAL] = raw
        return raw, full, True
    raise SystemExit(f"{path}: unexpected size {len(raw)} (want 524288 or 65536)")


def check_all(full, cal_only):
    if not cal_only:
        return [boot(full), boot_block_add(full), program(full), calibration(full),
                program_add(full), calibration_add(full)]
    sw = cal_sw(full)
    out = [calibration(full)]
    if sw in CAL_ADD32_REGIONS:
        r = calibration_add(full, sw)
        r["note"] = f"regions from built-in {sw} table"
        out.append(r)
    else:
        out.append(dict(name="Calibration (add)", kind="add32", at=0x72FFC, size=4,
                        stored=u32(full, 0x72FFC), computed=None, ranges=[],
                        note=f"SW {sw!r} unknown; regions live in program @0x6FDCE"))
    return out


def fix(full, cal_only):
    sw = cal_sw(full) if cal_only else None
    if not cal_only:
        put32(full, 0xBFF8, boot_block_add(full)["computed"])
        put32(full, 0x6FDAE, program_add(full)["computed"])
    if not cal_only or sw in CAL_ADD32_REGIONS:
        put32(full, 0x72FFC, calibration_add(full, sw)["computed"])
    if not cal_only:
        put16(full, 0x3C24, boot(full)["computed"])
        put16(full, 0x6FDE0, program(full)["computed"])
    put16(full, 0x73FE0, calibration(full)["computed"])


def fmt(r):
    width = 8 if r["kind"] == "add32" else 4
    st = f"{r['stored']:0{width}X}"
    if r["computed"] is None:
        return f"  {r['name']:<18} @0x{r['at']:05X} stored {st}  ---  ({r.get('note', '')})"
    ok = "OK " if r["stored"] == r["computed"] else "BAD"
    adj = 1 if r["kind"] == "add32" else 0  # add-32 ends are exclusive; print inclusive
    rng = ", ".join(f"0x{s:05X}-0x{t - adj:05X}" for s, t in r["ranges"])
    extra = f"  [{r['note']}]" if r.get("note") else ""
    return (f"  {r['name']:<18} @0x{r['at']:05X} stored {st} computed "
            f"{r['computed']:0{width}X}  {ok}  over {rng}{extra}")


def main(argv):
    args = [a for a in argv[1:] if not a.startswith("--")]
    flags = {a for a in argv[1:] if a.startswith("--")}
    if len(args) != 1 or flags - {"--fix", "--json"}:
        raise SystemExit(__doc__)
    path = args[0]
    raw, full, cal_only = load(path)
    if "--fix" in flags:
        fix(full, cal_only)
        if cal_only:
            raw[:] = full[CAL_BASE:CAL_BASE + CAL]
        Path(path).write_bytes(raw)
    results = check_all(full, cal_only)
    good = all(r["computed"] is None or r["stored"] == r["computed"] for r in results)
    if "--json" in flags:
        print(json.dumps(dict(file=path, size=len(raw), calibration_only=cal_only,
                              valid=good, results=results), indent=1))
    else:
        kind = "64 KB calibration (addresses below are flash offsets; file = flash - 0x70000)" if cal_only else "512 KB full image"
        print(f"{path}: {kind}, SW {cal_sw(full)}")
        for r in results:
            print(fmt(r))
        print("  all checksums valid" if good else "  CHECKSUM MISMATCH")
    return 0 if good else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
