import subprocess,sys,os,time,pathlib,signal
image,home,log=sys.argv[1:]
env=os.environ.copy();env.update(T3CODE_HOME=home,T3CODE_DEV_SEED='0',T3CODE_DISABLE_AUTO_UPDATE='true')
env.pop('ELECTRON_RUN_AS_NODE',None)
with open(log,'w') as f:
    p=subprocess.Popen([image,'--no-sandbox','--disable-gpu'],env=env,stdout=f,stderr=f,start_new_session=True)
    try:
        for i in range(180):
            if pathlib.Path(home,'bin/t3').exists():
                print('Packaged desktop installed generated launcher.',flush=True);time.sleep(2);break
            if p.poll() is not None: raise RuntimeError('Desktop exited: '+str(p.returncode))
            time.sleep(.5)
        else: raise RuntimeError('Launcher was not installed')
    finally:
        try:os.killpg(p.pid,signal.SIGTERM)
        except ProcessLookupError:pass
        try:p.wait(timeout=15)
        except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
