pip install crcmod --break-system-packages -q

python3 -c "
import struct, crcmod

crc32c = crcmod.predefined.mkCrcFun('crc-32c')

with open('/dev/nbd0','rb') as f:
    f.seek(1024)
    sb = f.read(1024)

uuid      = sb[104:120]
csum_seed = struct.unpack_from('<I', sb, 408)[0]
BSIZE     = 4096

def compute_bitmap_csum(bitmap_data):
    return crc32c(uuid + bitmap_data, csum_seed) & 0xFFFF

def compute_gdt_csum(g, entry):
    e = bytearray(entry)
    struct.pack_into('<H', e, 30, 0)
    return crc32c(uuid + struct.pack('<H', g) + bytes(e), csum_seed) & 0xFFFF

data = bytearray(open('/tmp/merged_gdt.bin','rb').read())

print('Fixing groups 0-12 only (zeroed by fast initialization)...')
with open('/dev/nbd0','rb') as f:
    for g in range(13):
        e = data[g*64:(g+1)*64]

        # Read actual inode bitmap (will be zeros for damaged groups)
        ib_block = struct.unpack_from('<I', e, 4)[0]
        f.seek(ib_block * BSIZE)
        ib_data = f.read(BSIZE)

        # Read actual block bitmap
        bb_block = struct.unpack_from('<I', e, 0)[0]
        f.seek(bb_block * BSIZE)
        bb_data = f.read(BSIZE)

        # Compute correct checksums from actual bitmap data
        ib_csum = compute_bitmap_csum(ib_data)
        bb_csum = compute_bitmap_csum(bb_data)

        struct.pack_into('<H', data, g*64+26, ib_csum)  # ib_csum_lo
        struct.pack_into('<H', data, g*64+50, 0)        # ib_csum_hi
        struct.pack_into('<H', data, g*64+24, bb_csum)  # bb_csum_lo
        struct.pack_into('<H', data, g*64+48, 0)        # bb_csum_hi

        # Recompute GDT entry checksum
        gdt_csum = compute_gdt_csum(g, data[g*64:(g+1)*64])
        struct.pack_into('<H', data, g*64+30, gdt_csum)

        print(f'  Group {g:2d}: ib_csum=0x{ib_csum:04x} '
              f'bb_csum=0x{bb_csum:04x} gdt_csum=0x{gdt_csum:04x}')

with open('/tmp/merged_gdt.bin','wb') as f:
    f.write(data)
print('Saved')
"

pkill -f nbd_server
nbd-client -d /dev/nbd0 2>/dev/null
sleep 1
python3 nbd_server_v9.py &
sleep 2
nbd-client 127.0.0.1 10809 /dev/nbd0 -N ""

e2fsck -n /dev/nbd0 2>&1 | head -10

ext4magic /dev/nbd0 \
  -s 4096 -n 32768 \
  -M \
  -a $(date -d "2023-01-01" +%s) \
  -d /mnt/recovered \
  2>&1 | tee /tmp/ext4magic.log
