import os, sys, subprocess, socket, time, pathlib, re, json
root=pathlib.Path(__file__).parent
run=root/time.strftime('run-%Y%m%d-%H%M%S'); run.mkdir()
for side, checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
    home=run/side; home.mkdir()
    env=dict(os.environ,T3CODE_DEV_SEED='0',NO_COLOR='1')
    cwd=pathlib.Path(checkout)/'apps/server'
    log=open(home/'server.raw.log','w')
    p=subprocess.Popen(['node','src/bin.ts','serve','--base-dir',str(home/'state'),'--port','37459','--no-browser'],cwd=cwd,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
    try:
        for n in range(120):
            if p.poll() is not None: raise RuntimeError('server stopped; inspect server.raw.log')
            try:
                with socket.create_connection(('127.0.0.1',37459),timeout=.2):
                    if (home/'state/userdata/server-runtime.json').exists() and 'Listening on' in (home/'server.raw.log').read_text(): break
                    time.sleep(.5)
            except OSError: time.sleep(.5)
        else: raise RuntimeError('server did not listen')
        r=subprocess.run(['node','src/bin.ts','pair','--base-dir',str(home/'state'),'--tailscale','--tailscale-serve-port','8459'],cwd=cwd,env=env,capture_output=True,text=True,timeout=90)
        direct=subprocess.run(['tailscale','serve','--https=8459','--bg','http://127.0.0.1:37459'],capture_output=True,text=True,timeout=30)
        prefs=json.loads(subprocess.check_output(['tailscale','debug','prefs']))
        status=json.loads(subprocess.check_output(['tailscale','status','--json']))
        serve=subprocess.check_output(['tailscale','serve','status'],text=True)
        out=f"{side.upper()} | Linux | normal user (uid {os.getuid()}) | Tailscale {status['Version']}\nCommit: "+subprocess.check_output(['git','rev-parse','HEAD'],cwd=cwd,text=True).strip()+f"\nTailscale: {status['BackendState']}; MagicDNS enabled; HTTPS capability present\nOperatorUser: {prefs.get('OperatorUser') or 'unset'}\nFresh isolated database; server listening on 127.0.0.1:37459\n\n$ node src/bin.ts pair --base-dir <scratch> --tailscale --tailscale-serve-port 8459\n"+r.stdout+r.stderr+f"\nExit: {r.returncode}\n\n$ tailscale serve --https=8459 --bg http://127.0.0.1:37459\n"+direct.stdout+direct.stderr+f"\nExit: {direct.returncode}\n\n$ tailscale serve status\n"+serve
        out=re.sub(r'\x1b\[[0-9;]*m','',out)
        out=out.replace(str(pathlib.Path(checkout)),'<checkout>').replace(str(run),'<scratch>')
        (run/f'{side}.txt').write_text(out)
        print(out,flush=True)
    finally:
        import signal
        os.killpg(p.pid,signal.SIGTERM); p.wait(timeout=20); log.close()
print('RUN_DIRECTORY='+str(run))
