from ops import *
assert not (HERE/'build-intent.json').exists(),'Reuse build intent'
base='contextra-analytics:demo-pr12-8f99462cc0'
baseline=json.loads((HERE/'baseline.json').read_text())
assert json.loads(cmd(['docker','image','inspect',base]))[0]['Id']==baseline['containers']['contextra-analytics-1']['image']
paths=sorted(set(cmd(['git','-C',str(REPO),'diff','--name-only']).splitlines()+cmd(['git','-C',str(REPO),'ls-files','--others','--exclude-standard']).splitlines()))
paths=[p for p in paths if p.startswith('app/')]
hashes={p:hashlib.sha256((REPO/p).read_bytes()).hexdigest() for p in paths}
for p in ('native/provider_branch/flight.cpp','native/provider_branch/Makefile'):
    hashes[p]=hashlib.sha256((REPO/p).read_bytes()).hexdigest()
binary=HERE/'native-build/libgstcontextraflight.so'
hashes['libgstcontextraflight.so']=hashlib.sha256(binary.read_bytes()).hexdigest()
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)
shutil.copyfile(binary,snapshot/binary.name);(snapshot/binary.name).chmod(0o555)
recipe='FROM '+base+'\nCOPY app/ /opt/contextra/app/\nCOPY libgstcontextraflight.so /opt/contextra/lib/libgstcontextraflight.so\n'
(snapshot/'Dockerfile').write_text(recipe)
tag='contextra-analytics:pr13-'+digest
save('build-intent.json',dict(base=base,base_id=baseline['containers']['contextra-analytics-1']['image'],hashes=hashes,tag=tag,recipe=recipe))
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>180:
            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)))
