#!/usr/bin/env python3
"""Probe 8: find the entry prototype index selected at the end of yY."""
STAGE2 = '/root/luad/samples/boulder/stage2.lua'
PAYLOAD = '/root/luad/samples/boulder/payload.bin'
OUT = '/tmp/opencode/dump_run8.luau'

SHIM = r'''
local __realprint = print
tick = function() return 0 end
time = function() return 0 end
warn = function() end
typeof = function(v) return type(v) end
__ENTRY = 0
__ENT = function(T, i)
	__ENTRY = __ENTRY + 1
	__realprint("ENTRY", __ENTRY, tostring(i), type(T[i]))
end
'''

def main():
    stage2 = open(STAGE2, 'rb').read().decode('latin-1')
    payload = open(PAYLOAD, 'rb').read()
    rlit = '"' + ''.join('\\x%02x' % b for b in payload) + '"'
    stage2 = stage2.replace('local R=...;', 'local R=buffer.fromstring(' + rlit + ');', 1)
    needle = 'u=(T[j[42]()])'
    assert stage2.count(needle) == 1, stage2.count(needle)
    stage2 = stage2.replace(needle, '__TMP=j[42]();__ENT(T,__TMP);u=(T[__TMP])', 1)
    out = SHIM + 'local __ok,__err=pcall(function()\n' + stage2 + '\nend)\n'
    out += '__realprint("EXEC", __ok, tostring(__err))\n'
    open(OUT, 'w').write(out)
    print("wrote", len(out))

if __name__ == '__main__':
    main()
