import argparse,subprocess,pathlib,time,os,hashlib
p=argparse.ArgumentParser(); p.add_argument('--checkout',required=True);p.add_argument('--home',required=True);p.add_argument('--output',required=True);p.add_argument('--port',required=True);a=p.parse_args()
out=pathlib.Path(a.output);out.mkdir(parents=True,exist_ok=True)
root=pathlib.Path(__file__).parent
video=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-video_size','1920x1080','-framerate','10','-i',os.environ['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p',str(out/'recording.mp4')])
terminal=subprocess.Popen(['gnome-terminal','--wait','--hide-menubar','--geometry=140x45+20+20','--title=T3 Connect CLI proof','--','python3',str(root/'prove-connect.py'),'--checkout',a.checkout,'--home',a.home,'--output',a.output,'--port',a.port])
def capture(name):
    target=out/(name+'.png')
    for attempt in range(10):
        subprocess.run(['import','-window','root',str(target)],check=True)
        time.sleep(.5)
        subprocess.run(['import','-window','root',str(out/'stability.png')],check=True)
        if target.read_bytes()==(out/'stability.png').read_bytes(): return
    raise RuntimeError('Capture did not stabilize')
try:
    deadline=time.monotonic()+480
    captured=False
    while time.monotonic()<deadline:
        if (out/'revocation-ready').exists() and not captured:
            capture('after-revocation');captured=True
        if (out/'done').exists():
            capture('after-restart');break
        if terminal.poll() is not None: raise RuntimeError('Terminal ended before proof completed')
        time.sleep(.25)
    else: raise RuntimeError('Proof did not finish')
    terminal.wait(timeout=30)
finally:
    if terminal.poll() is None: terminal.terminate();terminal.wait(timeout=20)
    video.send_signal(2);video.wait(timeout=20)
