from ops import *
paths = cmd(['git', '-C', str(REPO), 'diff', '--name-only']).splitlines() + cmd(['git', '-C', str(REPO), 'ls-files', '--others', '--exclude-standard']).splitlines()
paths = sorted(p for p in paths if p.startswith(('app/', 'native/')) and (REPO/p).is_file())
base = json.loads((HERE/'baseline.json').read_text())['containers']['contextra-analytics-1']['image']
hashes = {p:hashlib.sha256((REPO/p).read_bytes()).hexdigest() for p in paths}
digest = hashlib.sha256(json.dumps(hashes,sort_keys=True).encode()).hexdigest()[:10]
snapshot = HERE/('image-'+digest); snapshot.mkdir(mode=0o700)
for p in paths:
    target = snapshot/p; target.parent.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(REPO/p,target); target.chmod(0o644)
# Include the complete local plugin build inputs, never SDK or model replacements.
for source in (REPO/'native/frame_metadata').glob('*'):
    if source.is_file():
        target = snapshot/'native/frame_metadata'/source.name
        target.parent.mkdir(parents=True, exist_ok=True); shutil.copyfile(source,target); target.chmod(0o644)
plugin = '/opt/nvidia/deepstream/deepstream/lib/gst-plugins'
(snapshot/'Dockerfile').write_text('FROM '+base+'\nCOPY app/ /opt/contextra/app/\nCOPY native/frame_metadata/ /opt/contextra/native/frame_metadata/\nRUN make -C /opt/contextra/native/frame_metadata BUILD_DIR='+plugin+' '+plugin+'/libcontextra_rtp_time.so\n')
tag = 'contextra-analytics:input-lag-'+digest
save('build-intent-'+digest+'.json', dict(base=base,hashes=hashes,tag=tag))
assert shutil.disk_usage('/').free > 15*1024**3
with (HERE/('build-'+digest+'.log')).open('x') as log:
    p = subprocess.Popen(['docker','build','--pull=false','--network=none','--memory=2g','--cpu-period=100000','--cpu-quota=200000','-t',tag,str(snapshot)],env=dict(os.environ,DOCKER_BUILDKIT='0'),stdout=log,stderr=log)
    begin=time.monotonic()
    while p.poll() is None:
        if shutil.disk_usage('/').free < 15*1024**3 or time.monotonic()-begin > 180:
            p.terminate();p.wait(15);raise RuntimeError('BUILD_BOUND')
        time.sleep(1)
assert p.returncode == 0
image=json.loads(cmd(['docker','image','inspect',tag]))[0]['Id']
save('image-'+digest+'.json',dict(tag=tag,id=image,hashes=hashes))
print(json.dumps(dict(tag=tag,id=image)),flush=True)
