import struct

# Group 0 inode table at block 1070
# Virtual byte: 1070 * 4096 = 4,382,720
# Physical byte via chunk translation:
CHUNK = 128*512
LV_START = 5120000*512
BSIZE = 4096

it_virt = 1070 * BSIZE
group     = it_virt // (5*CHUNK)
in_group  = it_virt % (5*CHUNK)
chunk_idx = in_group // CHUNK
intra     = in_group % CHUNK

print(f'Group 0 inode table:')
print(f'  Virtual byte:  {it_virt}')
print(f'  Chunk group:   {group}')
print(f'  Chunk index:   {chunk_idx} (4=metadata)')
print(f'  Is metadata:   {chunk_idx == 4}')

if chunk_idx != 4:
    phys = LV_START + group*4*CHUNK + chunk_idx*CHUNK + intra
    print(f'  Physical byte: {phys}')
    with open('/dev/sda','rb') as f:
        f.seek(phys)
        data = f.read(256)
    nonzero = sum(1 for b in data if b != 0)
    print(f'  First inode nonzero bytes: {nonzero}/256')
    print(f'  First 32 bytes: {data[:32].hex()}')
else:
    print(f'  In PERC metadata chunk - reads as zeros')

# Check groups 0-15
print()
print('Checking which groups have inode tables in metadata chunks:')
for g in range(20):
    it_block = 1070 + g*512
    it_virt  = it_block * BSIZE
    in_group  = it_virt % (5*CHUNK)
    chunk_idx = in_group // CHUNK
    if chunk_idx == 4:
        print(f'  Group {g:2d}: inode table in METADATA CHUNK (reads as zeros)')
    else:
        phys = LV_START + (it_virt//(5*CHUNK))*4*CHUNK + chunk_idx*CHUNK + (it_virt%CHUNK)
        with open('/dev/sda','rb') as f:
            f.seek(phys)
            data = f.read(256)
        nonzero = sum(1 for b in data if b != 0)
        print(f'  Group {g:2d}: DATA chunk, nonzero={nonzero}/256')
