import os,subprocess,pathlib,sys,time,signal
root=pathlib.Path(os.environ['PROOF_OUTPUT']);side,action=sys.argv[1:]
script=root/(side+'-'+action+'-terminal.sh')
script.write_text('#!/bin/bash\nprintf "\\033]0;T3 Connect stopped-server proof\\007\\033[2J\\033[H"\npython3 '+str(root/'stopped-cli.py')+' '+side+' '+action+'\ntouch '+str(root/(side+'-'+action+'.done'))+'\nsleep 8\n')
f=open(root/(side+'-'+action+'-ffmpeg.log'),'w')
v=subprocess.Popen(['ffmpeg','-y','-f','x11grab','-video_size','1920x1080','-framerate','10','-i',os.environ['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-crf','22',str(root/(side+'-'+action+'-terminal.mp4'))],stdout=f,stderr=f)
t=subprocess.Popen(['gnome-terminal','--wait','--full-screen','--zoom=1.4','--','bash',str(script)])
try:
 while not (root/(side+'-'+action+'.done')).exists():
  if t.poll() is not None:raise RuntimeError('terminal exited before commands completed')
  time.sleep(.2)
 time.sleep(2)
 subprocess.run(['import','-window','root',str(root/(side+'-'+action+'-terminal.png'))],check=True)
 t.wait(timeout=30)
finally:
 v.send_signal(signal.SIGINT);v.wait(timeout=10);f.close()
