import os,sys,signal,time,json,datetime
pid=int(sys.argv[1]); duration=int(sys.argv[2]); out=sys.argv[3]
def descendants(p):
    result=[]
    try:
        children=open(f'/proc/{p}/task/{p}/children').read().split()
    except FileNotFoundError:return []
    for child in children: result+=descendants(int(child))+[int(child)]
    return result
pids=descendants(pid)+[pid]
with open(out,'w') as f:
    f.write(json.dumps({'event':'freeze','utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'durationSeconds':duration,'processCount':len(pids)})+'\n');f.flush()
    for p in pids:
        try:os.kill(p,signal.SIGSTOP)
        except ProcessLookupError:pass
    try:time.sleep(duration)
    finally:
        for p in pids[::-1]:
            try:os.kill(p,signal.SIGCONT)
            except ProcessLookupError:pass
        f.write(json.dumps({'event':'resume','utc':datetime.datetime.now(datetime.timezone.utc).isoformat()})+'\n')
