import os, sys, pathlib, subprocess, re, time, shutil
root=pathlib.Path(os.environ.get("EVIDENCE_RUN_DIR", pathlib.Path(__file__).resolve().parent / time.strftime("run-%Y%m%d-%H%M%S")))
root.mkdir(parents=True,exist_ok=True)
side, checkout=sys.argv[1:]
run=root/side
run.mkdir(exist_ok=True)
home=run/'home'; runtime=home/'runtime/versions/0.1.13'
runtime.mkdir(parents=True,exist_ok=True)
shutil.copy2(pathlib.Path(checkout)/'apps/server/dist-exe/t3',runtime/'t3')
(runtime/'node_modules').symlink_to(pathlib.Path(checkout)/'apps/server/node_modules',target_is_directory=True)
(runtime/'.install-complete').write_text('0.1.13')
old=run/'old-bin'; old.mkdir(exist_ok=True)
(old/'t3').write_text('#!/bin/sh\necho old-t3\n'); (old/'t3').chmod(0o755)
log=open(run/'transcript.txt','w')
def say(s):
 print(s,flush=True); log.write(s+'\n'); log.flush()
def call(args, env):
 p=subprocess.run(args,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
 say(p.stdout.rstrip()); return p
for label,dirname in [('spaces','new bin'),('metacharacters',"new'bin;$USER"),('ordinary','new-bin')]:
 print('\033[2J\033[H',end='',flush=True)
 say(f'{side.upper()} | '+ ('ffcd550046' if side=='before' else '7bd7fb4d21'))
 say('Linux x86_64 | POSIX /bin/sh | real standalone CLI 0.1.13')
 say('Old executable t3 first on PATH; isolated runtime built from this commit.')
 say('CASE: '+label+'\n')
 for flow in ['install.sh','t3 install']:
  bindir=run/(('shell-' if flow=='install.sh' else 'cli-')+dirname)
  env={**os.environ,'T3CODE_HOME':str(home),'T3CODE_VERSION':'0.1.13','T3CODE_INSTALL_BIN_DIR':str(bindir),'PATH':f'{old}:{bindir}:/usr/bin:/bin','NO_COLOR':'1','TERM':'dumb'}
  say('$ '+flow+'  [T3CODE_INSTALL_BIN_DIR='+str(bindir)+']')
  args=['sh',str(pathlib.Path(checkout)/'scripts/install.sh')] if flow=='install.sh' else [str(runtime/'t3'),'install']
  p=call(args,env)
  match=re.search(r'so run (.*?) to use this one\.',p.stdout)
  if match:
   cmd=match[1]+' --version'; say('$ '+cmd)
   q=call(['/bin/sh','-c',cmd],env); say('exit status: '+str(q.returncode))
   if q.returncode:
    import shlex
    say('$ '+shlex.quote(str(bindir/'t3'))+' --version  [quoted control]')
    q=call(['/bin/sh','-c',shlex.quote(str(bindir/'t3'))+' --version'],env); say('control exit status: '+str(q.returncode))
  else: say('ERROR: installer did not print the expected suggestion')
  say('')
 (run/(label+'.ready')).touch()
 while not (run/(label+'.ack')).exists(): time.sleep(.1)
log.close()
