#!/usr/bin/env python3
"""g93sc hdr patch — turns samsung's official M-C9349GGAA-1011.0[C10A].img
(odyssey oled g9, G93SC) into the patched M-C9349GGAA-0000.0[C10A].img.

what it changes (21 bytes, all inside the 7 hdr edids):
  * cta-861 hdr static metadata: desired max luminance 96 -> 138 (400 -> ~994 cd/m2)
  * hdr10+ vsvdb oui 90-84-8b -> 91-84-8b (block is ignored, no more "400" via hdr10+)
  * each touched edid block's checksum, so the image's 16-bit sum stays 0xC10A

refuses anything that isn't byte-identical to the stock 1011.0 image.
no warranty. flashing modified firmware can brick the monitor. your risk.

usage: python3 g93sc-hdr-patch.py "M-C9349GGAA-1011.0[C10A].img"
"""
import hashlib, os, sys

BASE_SHA = "de1e93809ec4d06ca9920d3b17daba52f520532bb7d2e19d3bbffce76f70ba8c"
OUT_SHA  = "7010cd670045c344a17b4d01d51a8ebaf57e171fa77f3d518b7b6ed2c7a4dee1"
SIZE = 8881856
OUT_NAME = "M-C9349GGAA-0000.0[C10A].img"
# (file offset, stock byte, patched byte)
PATCH = [
    (0x4B20F3, 0x60, 0x8A), (0x4B20FA, 0x90, 0x91), (0x4B2157, 0x47, 0x1C),
    (0x4B2281, 0x60, 0x8A), (0x4B2288, 0x90, 0x91), (0x4B22D7, 0xD8, 0xAD),
    (0x4B23F5, 0x60, 0x8A), (0x4B23FC, 0x90, 0x91), (0x4B2457, 0x7E, 0x53),
    (0x4B2D9F, 0x60, 0x8A), (0x4B2DAA, 0x90, 0x91), (0x4B2DD7, 0x34, 0x09),
    (0x4B2FA3, 0x60, 0x8A), (0x4B2FAE, 0x90, 0x91), (0x4B2FD7, 0xC3, 0x98),
    (0x4B399F, 0x60, 0x8A), (0x4B39AA, 0x90, 0x91), (0x4B39D7, 0x44, 0x19),
    (0x4B3BA3, 0x60, 0x8A), (0x4B3BAE, 0x90, 0x91), (0x4B3BD7, 0xD3, 0xA8),
]

def main():
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    src = sys.argv[1]
    data = bytearray(open(src, "rb").read())
    if len(data) != SIZE or hashlib.sha256(data).hexdigest() != BASE_SHA:
        sys.exit("not the stock 1011.0 image (size/sha-256 mismatch). nothing written.")
    for off, old, new in PATCH:
        if data[off] != old:
            sys.exit(f"unexpected byte at {off:#x}. nothing written.")
        data[off] = new
    if hashlib.sha256(data).hexdigest() != OUT_SHA or sum(data) & 0xFFFF != 0xC10A:
        sys.exit("result check failed. nothing written.")
    out = os.path.join(os.path.dirname(os.path.abspath(src)), OUT_NAME)
    open(out, "wb").write(data)
    print(f"wrote {out}\nsha-256 {OUT_SHA}\nput it alone on a fat32 stick, root folder, name unchanged.")

if __name__ == "__main__":
    main()
