#!/usr/bin/env python3
"""Runs the official git-lfs binary unchanged; bounds its run time to 5% wall time.
Only filter-process is limited, and only in repos containing .git/proof-slow-lfs.
No filter protocol, files, or T3 code is replaced. Child PID is captured at spawn.
"""
import os,sys,subprocess,time,signal,json
from pathlib import Path
binary=Path(__file__).parent/'git-lfs-3.4.1/git-lfs'
p=subprocess.Popen([str(binary),*sys.argv[1:]])
log=os.environ.get('PROOF_LFS_EVENTS')
if log:
 with open(log,'a') as f: f.write(json.dumps({'at':time.time(),'pid':p.pid,'action':'spawn','args':sys.argv[1:],'repo':Path.cwd().name})+'\n')
slow=Path('.git/proof-slow-lfs').exists() and 'filter-process' in sys.argv
try:
 while p.poll() is None:
  if slow:
   time.sleep(.02)
   if p.poll() is not None: break
   os.kill(p.pid,signal.SIGSTOP)
   time.sleep(.38)
   os.kill(p.pid,signal.SIGCONT)
  else: p.wait()
finally:
 if p.poll() is None:
  p.kill(); p.wait()
sys.exit(p.returncode)
