import subprocess,os,time,pathlib,sys
root=pathlib.Path(__file__).parent
side,repo,offset=sys.argv[1:]
video=root/(side+'.mp4');shot=root/(side+'.png');done=root/(side+'.done')
ff=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','x11grab','-video_size','1368x1000','-framerate','10','-i',os.environ['DISPLAY'],'-c:v','libx264','-preset','ultrafast','-pix_fmt','yuv420p',str(video)],stdin=subprocess.PIPE)
terminal=subprocess.Popen(['gnome-terminal','--wait','--geometry=150x54+0+0','--title=Shared provider CLI update — '+side,'--','python3',str(root/'run.py'),side,repo,offset])
try:
 while not done.exists():
  if terminal.poll() is not None: raise RuntimeError('Terminal exited before reproduction finished')
  time.sleep(.25)
 time.sleep(1)
 subprocess.run(['import','-window','root','-crop','1368x1000+0+0',str(shot)],check=True)
 time.sleep(.5)
 subprocess.run(['import','-window','root','-crop','1368x1000+0+0',str(root/(side+'-stable.png'))],check=True)
 ff.communicate(b'q',timeout=10)
 terminal.wait(timeout=20)
finally:
 if ff.poll() is None: ff.terminate();ff.wait()
 if terminal.poll() is None: terminal.terminate();terminal.wait()
