#!/usr/bin/env python3
"""Dump the global string pool from a resources.arsc file (dependency-free)."""
import struct, sys

def read_pool(data, off):
    ctype, hsize, csize = struct.unpack_from('<HHI', data, off)
    assert ctype == 0x0001, f"not a string pool at {off}"
    (scount, stycount, flags, sstart, stystart) = struct.unpack_from('<IIIII', data, off+8)
    is_utf8 = (flags & (1<<8)) != 0
    offs = [struct.unpack_from('<I', data, off+28+4*i)[0] for i in range(scount)]
    base = off + sstart
    res = []
    for o in offs:
        p = base + o
        if is_utf8:
            if data[p] & 0x80: p += 2
            else: p += 1
            if data[p] & 0x80:
                blen = ((data[p]&0x7F)<<8)|data[p+1]; p += 2
            else:
                blen = data[p]; p += 1
            res.append(data[p:p+blen].decode('utf-8','replace'))
        else:
            clen = data[p]|(data[p+1]<<8)
            p += 2
            if clen & 0x8000:
                clen = ((clen&0x7FFF)<<16)|(data[p]|(data[p+1]<<8)); p += 2
            res.append(data[p:p+clen*2].decode('utf-16-le','replace'))
    return res

data = open(sys.argv[1],'rb').read()
# First chunk is RES_TABLE (0x0002) header 12 bytes; then package? Actually
# the global string pool follows the table header. Find first 0x0001 chunk.
off = 0
ctype, hsize, csize = struct.unpack_from('<HHI', data, 0)
# table header size = hsize; global pool starts right after
pool_off = hsize
strings = read_pool(data, pool_off)
for s in strings:
    print(repr(s))
