import pathlib, subprocess, os, sys, struct
root=pathlib.Path(sys.argv[1]).resolve()
out=pathlib.Path(sys.argv[2]).resolve()
out.mkdir(parents=True,exist_ok=True)
helper=root/'native/kde-snap-shot/target/x86_64-unknown-linux-gnu/release/t3-kde-snap-shot'
original=helper.read_bytes()
assert b'GLIBC_2.39\0' in original
# Fault injection: promote the real helper's 2.39 version need to 2.40.
# Update the corresponding ELF version hash as well as its dynamic string.
data=bytearray(original.replace(b'GLIBC_2.39\0',b'GLIBC_2.40\0'))
def elfhash(s):
    h=0
    for c in s:
        h=(h<<4)+c; g=h&0xf0000000
        if g: h ^= g>>24
        h &= ~g
    return h
old=struct.pack('<I',elfhash(b'GLIBC_2.39'))
new=struct.pack('<I',elfhash(b'GLIBC_2.40'))
assert data.count(old)>=1
data=data.replace(old,new)
env={**os.environ,'T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS':'1','T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR':'1'}
args=['node','scripts/build-desktop-artifact.ts','--platform','linux','--target','deb','--arch','x64','--skip-build','--output-dir',str(out/'artifacts'),'--verbose']
try:
    helper.write_bytes(data)
    inspection=subprocess.run(['readelf','-W','-V',str(helper)],capture_output=True,text=True,check=True).stdout
    with (out/'raw-build.log').open('w') as log:
        p=subprocess.run(args,cwd=root,env=env,stdout=log,stderr=subprocess.STDOUT)
    raw=(out/'raw-build.log').read_text()
    # Public transcript hides only the local build and temporary staging roots.
    import re
    clean=raw.replace(str(root),'<checkout>').replace(str(out),'<output>')
    clean=re.sub(r'/tmp/t3code-desktop-[^/\s]+','<stage>',clean)
    clean=clean.replace(str(pathlib.Path.home()),'<home>')
    text='Fault injection: real KDE helper GLIBC_2.39 version need and ELF hash promoted to GLIBC_2.40.\n'
    text+='Command: T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS=1 T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR=1 node scripts/build-desktop-artifact.ts --platform linux --target deb --arch x64 --skip-build --output-dir <output>/artifacts --verbose\n'
    text+='readelf version NEEDS: '+ '\n'.join(line.strip() for line in inspection.splitlines() if 'Name: GLIBC_2.40' in line)+'\n'
    text+=clean+f'\nPACKAGING_EXIT={p.returncode}\n'
    (out/'transcript.txt').write_text(text)
    print('PACKAGING_EXIT='+str(p.returncode))
    print('\n'.join(line for line in clean.splitlines() if 'GLIBC_2.40' in line or 'linux-glibc' in line or 'Done.' in line))
finally:
    helper.write_bytes(original)
