"""Run the real generated remote bootstrap, without a test runner.
Generate base-runner.sh and head-runner.sh from each checkout with:
node --experimental-strip-types --input-type=module -e 'import {buildRemoteT3RunnerScript} from "./packages/ssh/src/tunnel.ts"; process.stdout.write(buildRemoteT3RunnerScript({archiveVersion:"0.1.9"}));'
Place the official v0.1.9 linux-x64 archive and SHA256SUMS beside this driver.
"""
import pathlib, subprocess, shutil, os, datetime, hashlib, json
root=pathlib.Path(__file__).resolve().parent
run=root/('run-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
run.mkdir()
archive='t3-0.1.9-linux-x64.tar.gz'
expected=next(x.split()[0] for x in (root/'SHA256SUMS').read_text().splitlines() if x.endswith(archive))
assert hashlib.sha256((root/archive).read_bytes()).hexdigest()==expected
results=[]
for side,sha in [('base','fd8e386f7f259070899553e55c99a2a49a378480'),('head','da7d9bd54803db2bd964210178c5aba1e2537b8b')]:
 for gzip in [False,True]:
  name=side+('-with-gzip' if gzip else '-no-gzip')
  folder=run/name; folder.mkdir(); home=folder/'home'; home.mkdir(); bin=folder/'bin'; bin.mkdir()
  for tool in ['sh','mkdir','mktemp','cat','rm','grep','cut','sha256sum','tar','mv']+(['gzip'] if gzip else []):
   (bin/tool).symlink_to(shutil.which(tool))
  (bin/'uname').write_text('#!/bin/sh\ncase "$1" in -s) echo Linux ;; -m) echo x86_64 ;; esac\n'); (bin/'uname').chmod(0o755)
  (bin/'curl').write_text('#!/bin/sh\nfor last; do :; done\nfor a; do case "$a" in http*) src="'+str(root)+'/端${a##*/}" ;; esac; done\nprintf "Served local release file: %s\\n" "${src##*/}" >&2\nexec cat "$src" > "$last"\n'.replace('端','')); (bin/'curl').chmod(0o755)
  result=subprocess.run(['/bin/sh',str(root/(side+'-runner.sh')),'--version'],env={'HOME':str(home),'PATH':str(bin)},capture_output=True,text=True)
  log=f'''SSH remote bootstrap command capture
Commit: {sha}
Host: Linux x86_64; /bin/sh; GNU tar
Fresh HOME; restricted PATH; gzip {'present (control)' if gzip else 'absent'}
Official release: v0.1.9; SHA256 verified before serving
Command: /bin/sh generated-runner.sh --version

{result.stderr}{result.stdout}
Exit status: {result.returncode}
'''
  (run/(name+'.txt')).write_text(log)
  print(log)
  results.append({'name':name,'exit':result.returncode,'stdout':result.stdout,'stderr':result.stderr})
(run/'results.json').write_text(json.dumps(results,indent=2))
print('CAPTURE_DIRECTORY='+str(run))
