import os, sys, socket, json, time, signal, subprocess
mode, duration, code, label, root, sock = sys.argv[1:7]
duration=int(duration); code=int(code)
s=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM); s.connect(sock)
start=time.monotonic_ns()
def event(kind, **kw):
    s.sendall((json.dumps(dict(kind=kind,label=label,pid=os.getpid(),ppid=os.getppid(),pgid=os.getpgrp(),mono_ns=time.monotonic_ns(),**kw))+'\n').encode())
def term(sig,frame):
    event('TERM', policy='cooperative' if mode=='cooperative' else 'ignore')
    if mode=='cooperative': sys.exit(1)
signal.signal(signal.SIGTERM,term)
if mode=='leader':
    r,w=os.pipe()
    child=subprocess.Popen([sys.executable,__file__,'hostile',str(duration),'0',label+'.child',root,sock],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,pass_fds=(w,),env=dict(os.environ,FIXTURE_READY_FD=str(w)))
    os.close(w); os.read(r,1); os.close(r)
    event('LEADER_EXIT',child=child.pid,code=code); sys.exit(code)
event('READY',duration_ms=duration,mode=mode)
if 'FIXTURE_READY_FD' in os.environ:
    os.write(int(os.environ['FIXTURE_READY_FD']),b'1'); os.close(int(os.environ['FIXTURE_READY_FD']))
if mode=='overflow':
    print('X'*2048,flush=True); event('OVERFLOW_EMITTED')
elif mode not in ('transport','hostile'):
    print('OUT:'+label,flush=True); print('ERR:'+label,file=sys.stderr,flush=True)
time.sleep(duration/1000)
with open(os.path.join(root,label+'.marker'),'w') as f: f.write('natural completion\n')
event('NATURAL_EXIT',code=code)
if mode=='transport':
    # git-upload-pack owns the real protocol after the controlled transport wait.
    s.close(); os.execvp('git',['git','upload-pack',os.environ['FIXTURE_ORIGIN']])
sys.exit(code)
