from ops import *
assert not (HERE/'build-intent.json').exists()
base='sha256:1c433589cf304154118f46d97411c167a92a29e6d3802f00ba3624297eb77a2e'
paths=['app/single_decode_pipeline.py']
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-source';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)
recipe='FROM '+base+'\nCOPY app/ /opt/contextra/app/\n'
(snapshot/'Dockerfile').write_text(recipe)
tag='contextra-analytics:pr13-framefix-'+digest
save('build-intent.json',dict(base=base,hashes=hashes,tag=tag,recipe=recipe))
assert shutil.disk_usage('/').free>15*1024**3
with (HERE/'build.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)
    start=time.monotonic();lowest=shutil.disk_usage('/').free
    while p.poll() is None:
        lowest=min(lowest,shutil.disk_usage('/').free)
        if lowest<15*1024**3 or time.monotonic()-start>150:
            p.terminate();p.wait(15);raise RuntimeError('BUILD_RESOURCE_BOUND')
        time.sleep(1)
assert p.returncode==0,'BUILD_FAILED_NO_BLIND_RETRY'
image=json.loads(cmd(['docker','image','inspect',tag]))[0]['Id']
save('image.json',dict(tag=tag,id=image,lowest_root_bytes=lowest))
print(json.dumps(dict(tag=tag,id=image)))
