#!/usr/bin/env python3
"""Run an unpacked standalone archive with its self-alias ahead of real Node.
Usage: run-standalone.py SIDE INSTALL_DIRECTORY REAL_NODE PORT
Fresh state lives beside this script, under SIDE/run-TIMESTAMP.
"""
from pathlib import Path
import datetime, json, os, sys, subprocess
side, install_arg, node_arg, port = sys.argv[1:]
install = Path(install_arg).resolve()
node = Path(node_arg).resolve()
run = Path(__file__).parent / side / ('run-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))
for name in ('home', 'alias', 'realnode', 'project'):
    (run / name).mkdir(parents=True, exist_ok=True)
# Use the genuine pinned package. Its installation is setup, before the alias PATH.
prefix = run/'state/tools/expo-device-hub/0.26.1'
setup_env = dict(os.environ, HOME=str(run/'home'), PATH=str(node.parent)+':/usr/bin:/bin')
subprocess.run([str(node), str(node.parent/'npm'), 'install', '--prefix', str(prefix),
                '--no-fund', '--no-audit', 'expo-device-hub@0.26.1'],
               env=setup_env, check=True)
(prefix/'.install-complete').write_text('0.26.1\n')
(run/'alias/node').symlink_to(install/'t3')
(run/'realnode/node').symlink_to(node)
path = f'{run}/alias:{run}/realnode:/usr/bin:/bin'
(run/'home/.bash_profile').write_text('export PATH="' + path + '"\n')
env = dict(os.environ, HOME=str(run/'home'), SHELL='/bin/bash', PATH=path,
           T3CODE_DEV_SEED='0', T3CODE_NO_BROWSER='1')
for key in ('T3CODE_HOME','VITE_HTTP_URL','VITE_WS_URL','VITE_DEV_SERVER_URL','T3CODE_DEV_AUTH_TOKEN'):
    env.pop(key, None)
(run/'run.json').write_text(json.dumps({'pid':os.getpid(),'port':int(port),'install':str(install),'run':str(run)},indent=2))
os.chdir(run/'project')
os.execve(install/'t3', [str(install/'t3'), '--base-dir', str(run/'state'), '--host','127.0.0.1','--port',port,'--no-browser','--auto-bootstrap-project-from-cwd'], env)
