#!/usr/bin/env python3
"""pc98_ips_patch.py - apply an IPS patch to a file inside a PC-98 hard-disk image.

Works on raw images (MiSTer .vhd) and on HDI/NHD images with a header: the
FAT12/FAT16 partition is found by scanning for its boot sector. The patched
file keeps its size and clusters; only the changed bytes are written.

  python3 pc98_ips_patch.py IMAGE PATCH.ips PATH/IN/IMAGE [--before SHA256] [--after SHA256] [--partition N] [--dry-run]

Example (Doom on a MiSTer disk image):
  python3 pc98_ips_patch.py PC98_Doom1.vhd Doom_PC98_86Music_Upgrade.ips DOOM/DOOM.EXE \\
      --before 09e9ecbe0e78a6f2d5b541a62378fac4d073c31f41be09ea7c485b6bc85e8a3d

Always work on a copy of the image. Nothing is written unless the file's
current hash matches --before (when given) and the patched result matches
--after (when given).
"""
import argparse
import hashlib
import struct
import sys


def find_partitions(img, limit=100 << 20):
    """Return byte offsets of FAT boot sectors (256-byte steps, for 256-byte-sector HDIs)."""
    seen = []
    chunk = 1 << 20
    for base in range(0, limit, chunk):
        img.seek(base)
        buf = img.read(chunk + 64)
        for k in range(0, min(chunk, len(buf) - 63), 256):
            b = buf[k:k + 64]
            if b[0] not in (0xEB, 0xE9):
                continue
            bps = struct.unpack('<H', b[11:13])[0]
            spc = b[13]
            res = struct.unpack('<H', b[14:16])[0]
            nf = b[16]
            if bps in (256, 512, 1024, 2048) and spc in (1, 2, 4, 8, 16, 32, 64, 128) and nf in (1, 2) and res >= 1:
                seen.append(base + k)
        if len(buf) <= chunk:
            break
    return seen


class Fat:
    def __init__(self, img, base):
        self.img, self.base = img, base
        img.seek(base + 11)
        bps, spc, res, nf, nroot, tot16, _, spf = struct.unpack('<HBHBHHBH', img.read(13))
        img.seek(base + 32)
        tot32 = struct.unpack('<I', img.read(4))[0]
        self.bps, self.cl = bps, spc * bps
        self.fat = base + res * bps
        self.root = self.fat + nf * spf * bps
        self.nroot = nroot
        self.data = self.root + nroot * 32
        total = tot16 or tot32
        clusters = (total * bps - (self.data - base)) // self.cl
        self.fat12 = clusters < 4085
        img.seek(self.fat)
        self.fattab = img.read(spf * bps)

    def next(self, c):
        if self.fat12:
            v = struct.unpack('<H', self.fattab[c * 3 // 2:c * 3 // 2 + 2])[0]
            v = v >> 4 if c & 1 else v & 0xFFF
            return v if v < 0xFF8 else None
        v = struct.unpack('<H', self.fattab[2 * c:2 * c + 2])[0]
        return v if v < 0xFFF8 else None

    def chain(self, c):
        out = []
        while c is not None and 2 <= c and len(out) < 1 << 20:
            out.append(c)
            c = self.next(c)
        return out

    def read_chain(self, clus):
        parts = []
        for c in clus:
            self.img.seek(self.data + (c - 2) * self.cl)
            parts.append(self.img.read(self.cl))
        return b''.join(parts)

    def lookup(self, path):
        self.img.seek(self.root)
        ents = self.img.read(self.nroot * 32)
        parts = [p for p in path.replace('\\', '/').upper().split('/') if p]
        for i, name in enumerate(parts):
            hit = None
            for k in range(0, len(ents), 32):
                e = ents[k:k + 32]
                if not e or e[0] == 0:
                    break
                if e[0] == 0xE5 or e[11] == 0x0F or e[11] & 0x08:
                    continue
                nm = (e[:8].decode('latin1').rstrip() + '.' + e[8:11].decode('latin1').rstrip()).rstrip('.')
                if nm == name:
                    hit = (struct.unpack('<H', e[26:28])[0], struct.unpack('<I', e[28:32])[0], e[11])
                    break
            if hit is None:
                return None
            first, size, attr = hit
            if i < len(parts) - 1:
                if not attr & 0x10:
                    return None
                ents = self.read_chain(self.chain(first))
            else:
                return first, size
        return None


def apply_ips(data, patch):
    if patch[:5] != b'PATCH':
        raise SystemExit('not an IPS file')
    out = bytearray(data)
    i = 5
    while True:
        if patch[i:i + 3] == b'EOF':
            break
        off = int.from_bytes(patch[i:i + 3], 'big')
        size = int.from_bytes(patch[i + 3:i + 5], 'big')
        i += 5
        if size == 0:                                   # RLE record
            run = int.from_bytes(patch[i:i + 2], 'big')
            val = patch[i + 2:i + 3]
            i += 3
            chunk = val * run
        else:
            chunk = patch[i:i + size]
            i += size
        if off + len(chunk) > len(out):
            raise SystemExit('patch would change the file size; this tool only patches in place')
        out[off:off + len(chunk)] = chunk
    return bytes(out)


def main():
    ap = argparse.ArgumentParser(description='Apply an IPS patch to a file inside a PC-98 disk image.')
    ap.add_argument('image')
    ap.add_argument('patch')
    ap.add_argument('path', help='file inside the image, e.g. DOOM/DOOM.EXE')
    ap.add_argument('--before', help='expected SHA-256 of the unpatched file')
    ap.add_argument('--after', help='expected SHA-256 of the patched file')
    ap.add_argument('--partition', type=int, default=None, help='partition number if the image has several (1 = first)')
    ap.add_argument('--dry-run', action='store_true', help='check and report, write nothing')
    a = ap.parse_args()

    patch = open(a.patch, 'rb').read()
    with open(a.image, 'rb' if a.dry_run else 'r+b') as img:
        parts = find_partitions(img)
        if not parts:
            raise SystemExit('no FAT partition found in the image')
        candidates = [parts[a.partition - 1]] if a.partition else parts
        found = None
        for base in candidates:
            try:
                fat = Fat(img, base)
                hit = fat.lookup(a.path)
            except Exception:
                continue
            if hit:
                found = (fat, hit)
                break
        if not found:
            raise SystemExit('%s not found in the image' % a.path)
        fat, (first, size) = found
        clus = fat.chain(first)
        cur = fat.read_chain(clus)[:size]
        h0 = hashlib.sha256(cur).hexdigest()
        print('found %s (%d bytes) in the partition at byte %d' % (a.path, size, fat.base))
        print('current SHA-256: %s' % h0)
        if a.after and h0.lower() == a.after.lower():
            print('the file already has this patch; nothing to do')
            return
        if a.before and h0.lower() != a.before.lower():
            raise SystemExit('the file does not match --before; not patching')
        new = apply_ips(cur, patch)
        h1 = hashlib.sha256(new).hexdigest()
        if new == cur:
            print('the file already has this patch; nothing to do')
            return
        if a.after and h1.lower() != a.after.lower():
            raise SystemExit('the patched result would not match --after; not patching')
        diff = [i for i in range(size) if cur[i] != new[i]]
        print('patched SHA-256: %s (%d bytes change)' % (h1, len(diff)))
        if a.dry_run:
            print('dry run: nothing written')
            return
        for i in diff:
            img.seek(fat.data + (clus[i // fat.cl] - 2) * fat.cl + i % fat.cl)
            img.write(new[i:i + 1])
        img.flush()
        check = fat.read_chain(clus)[:size]
        if hashlib.sha256(check).hexdigest() != h1:
            raise SystemExit('verification failed after writing!')
        print('done: %s patched and verified' % a.path)


if __name__ == '__main__':
    main()
