import os,sys,json,subprocess,time,pathlib,socket
repo,out=sys.argv[1:3]
p=pathlib.Path(out);p.mkdir(parents=True)
node_binary=subprocess.check_output(['node','-p','process.execPath'],text=True).strip()
s=json.loads(subprocess.check_output(['tailscale','status','--json']))
dns=s['Self']['DNSName'].rstrip('.')
ip=next(x for x in s['TailscaleIPs'] if ':' not in x)
(p/'network.json').write_text(json.dumps({'dns':dns,'ip':ip}))
(p/'hosts').write_text('127.0.0.1 localhost\n::1 localhost\n100.101.102.103 '+dns+'\n')
# A pair of Unix relays keeps both network namespaces isolated while real tailscaled
# terminates TLS and forwards to the desktop backend, rather than to another app.
children=[]
try:
 for args in [ ['socat','TCP-LISTEN:23773,bind=127.0.0.1,reuseaddr,fork','UNIX-CONNECT:'+out+'/backend.sock'], ['socat','UNIX-LISTEN:'+out+'/https.sock,fork','TCP:'+ip+':445'] ]:
  children.append(subprocess.Popen(args,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL))
 env={**os.environ,'XDG_DATA_HOME':out+'/keyring','T3CODE_DEV_SEED':'0'}
 driver=str(pathlib.Path(__file__).with_name('desktop-driver.mjs'))
 ret=subprocess.call(['sudo','-n','unshare','-nm',__import__('shutil').which('headless-desktop'),node_binary,driver,repo,out,'prove'],env=env)
 sys.exit(ret)
finally:
 for c in children:c.terminate()
 for c in children:c.wait()
 subprocess.check_call(['sudo','-n','chown','-R',str(os.getuid())+':'+str(os.getgid()),out])
