#!/usr/bin/env python3
"""DF-3246/DF-3257: minimal plain-ISO9660 image (no RRIP/SUSP/Joliet)."""
import struct, sys

BSZ = 2048
def b733(v): return struct.pack('<I', v) + struct.pack('>I', v)
def b723(v): return struct.pack('<H', v) + struct.pack('>H', v)

def dirrec(name, extent, size, flags):
    nb = name.encode() if isinstance(name, str) else name
    body = b733(extent) + b733(size) + bytes(7) + bytes([flags, 0, 0]) + b723(1)
    body += bytes([len(nb)]) + nb
    if len(body) % 2:
        body += b'\x00'
    return bytes([2 + len(body), 0]) + body

root = bytearray(BSZ); off = 0
for nm in (b'\x00', b'\x01'):
    r = dirrec(nm, 32, BSZ, 2); root[off:off+len(r)] = r; off += len(r)
r = dirrec('NAME;1', 33, 11, 0); root[off:off+len(r)] = r
data = b'hello cd9660'[:11].ljust(11)

volspace = 40
pvd = bytearray(BSZ)
pvd[0] = 1; pvd[1:6] = b'CD001'; pvd[6] = 1
pvd[8:40] = b'DF3246_PVD'.ljust(32)[:32]
pvd[40:72] = b'DF3246VOL'.ljust(32)
pvd[80:88] = b733(volspace)            # volume space size
pvd[120:124] = b723(1)                 # volume set size
pvd[124:128] = b723(1)                 # volume sequence number
pvd[128:132] = b723(BSZ)               # logical block size
pvd[132:140] = b733(10)                # path table size
pvd[140:144] = struct.pack('<I', 0)    # L path table loc (none)
pvd[144:148] = struct.pack('<I', 0)
pvd[148:152] = struct.pack('>I', 0)    # M path table loc
pvd[152:156] = struct.pack('>I', 0)
rr = dirrec(b'\x00', 32, BSZ, 2)
pvd[156:156+len(rr)] = rr              # root directory record

vdst = bytearray(BSZ)
vdst[0] = 255; vdst[1:6] = b'CD001'; vdst[6] = 1

img = bytearray(BSZ * 40)
img[16*BSZ:17*BSZ] = pvd
img[17*BSZ:18*BSZ] = vdst
img[32*BSZ:33*BSZ] = root
img[33*BSZ:33*BSZ+len(data)] = data
open(sys.argv[1], 'wb').write(bytes(img))
print("wrote %s" % sys.argv[1])
