import pathlib, subprocess, sys, tempfile, os
package = pathlib.Path(sys.argv[1]).resolve()
side, sha, output = sys.argv[2:]
output = pathlib.Path(output)
output.mkdir(parents=True, exist_ok=True)
lines = [f'Side: {side}', f'Commit: {sha}', 'Build environment: Ubuntu 24.04 x86_64, glibc 2.39', 'Build command: node scripts/build-desktop-artifact.ts --platform linux --target deb --arch x64', '']
def run(args):
    p = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    return p.returncode, p.stdout
rc, depends = run(['dpkg-deb','-f',str(package),'Depends'])
lines += ['$ dpkg-deb -f T3-Code-0.1.9-amd64.deb Depends', depends.strip(), f'exit={rc}', '']
root = output/'payload'
subprocess.run(['dpkg-deb','-x',str(package),str(root)],check=True)
requirements=[]
for p in sorted(root.rglob('*')):
    if not p.is_file() or p.is_symlink(): continue
    with p.open('rb') as f: magic=f.read(4)
    if magic != b'\x7fELF': continue
    rc, text = run(['readelf','-W','-V',str(p)])
    in_needs=False
    versions=[]
    import re
    for line in text.splitlines():
        if line.startswith('Version '): in_needs=line.startswith('Version needs section ')
        if in_needs:
            match=re.search(r'Name: GLIBC_(\d+(?:\.\d+)+)',line)
            if match: versions.append(match[1])
    if versions:
        maximum=max(versions,key=lambda v:tuple(map(int,v.split('.'))))
        requirements.append((str(p.relative_to(root)),maximum))
lines += ['$ readelf -W -V <every ELF in extracted package> (maximum version NEEDS per ELF)']
lines += [f'{name}: GLIBC_{version}' for name,version in requirements]
lines += ['','Environment: fresh debian:12 container, amd64, default apt repositories.']
command = '''export DEBIAN_FRONTEND=noninteractive
cat /etc/os-release | head -4
getconf GNU_LIBC_VERSION
apt-get update -qq
apt-get install -y /evidence/package.deb
install_rc=$?
echo "APT_INSTALL_EXIT=$install_rc"
dpkg-query -W -f='${Status}\\n' t3code 2>&1
if [ "$install_rc" = 0 ]; then
  '/opt/T3 Code (Beta)/resources/kde-capture/t3-kde-snap-shot' --help
  echo "KDE_HELPER_EXIT=$?"
fi
'''
rc, container = run(['docker','run','--rm','--network','bridge','-v',f'{package}:/evidence/package.deb:ro','debian:12','sh','-c',command])
(output/'apt-output.txt').write_text(container)
# Keep the entire runtime output; no local host paths are emitted by the container.
lines += ['$ apt-get install -y /evidence/package.deb', container, f'container exit={rc}']
(output/'transcript.txt').write_text('\n'.join(lines)+'\n')
print('\n'.join(lines[:9]))
print('\n'.join(line for line in container.splitlines() if any(x in line for x in ['libc6','APT_INSTALL_EXIT','KDE_HELPER_EXIT','GLIBC_','install ok installed','glibc '])))
