CHUNK = 128*512  # 65536 bytes
BSIZE = 4096

# Working blocks:
# 9262  (root dir)   -> chunk_idx=3, works
# 6300141 (volumes)  -> chunk_idx=3, works  
# 6299897 (ptero)    -> chunk_idx=3, works

# Failing block:
# 5251104 (var)      -> chunk_idx=4, fails

# All working blocks have chunk_idx=3
# The failing block has chunk_idx=4

# What if the issue isn't our translation formula
# but that block 5251104 was written when the filesystem
# was mounted through the PERC, and the PERC stored it
# in a way we can't access without the controller?

# Let's find MORE blocks that work to see if chunk_idx matters:
# Check the /boot, /home, /usr directories

import subprocess, struct

for path, inode in [('boot',2621441), ('home',2097153), ('usr',5505025),
                     ('etc',4456449), ('tmp',786433)]:
    r = subprocess.run(['istat','/dev/nbd0',str(inode)],
                      capture_output=True, text=True)
    for line in r.stdout.splitlines():
        if 'Direct Blocks' in line:
            pass
        elif line.strip() and all(c.isdigit() or c==' ' for c in line.strip()):
            blocks = [int(x) for x in line.split() if x.strip()]
            for b in blocks:
                virt = b * BSIZE
                group     = virt // (5*CHUNK)
                in_group  = virt % (5*CHUNK)
                chunk_idx = in_group // CHUNK
                print(f'/{path} block={b} chunk_idx={chunk_idx}')
