#!/usr/bin/env python3
import hashlib,json,pathlib,tarfile
here=pathlib.Path(__file__).resolve().parent;business=here.parents[4]/'zhctproject'/'store'
sha={x.split(None,1)[1]:x.split(None,1)[0] for x in (here/'SOURCE_SHA256.txt').read_text().splitlines()}
changed=json.loads((here/'CANDIDATE_TDD.json').read_bytes())['source_sha256']
for rel,proof in changed.items():
    assert sha[rel]==proof['original']
    assert hashlib.sha256((business/rel).read_bytes()).hexdigest()==proof['candidate']
    sha[rel]=proof['candidate']
(here/'GREEN_SOURCE_SHA256.txt').write_text(''.join(h+'  '+rel+'\n' for rel,h in sha.items()))
with tarfile.open('/tmp/cdx-catalog-green.tar.gz','w:gz') as archive:
    archive.add(here/'GREEN_SOURCE_SHA256.txt',arcname='SOURCE_SHA256.txt',recursive=False)
    for rel in changed:archive.add(business/rel,arcname='source/'+rel,recursive=False)
    for name in ['worker.php','index.php','green_prepare.php','green_postcheck.php','native_stats.php','cleanup.php','export_evidence.php','ResponseContractTest.php']:
        archive.add(here/name,arcname=name,recursive=False)
print(json.dumps({'source_files_changed':len(changed),'green_manifest_sha256':hashlib.sha256((here/'GREEN_SOURCE_SHA256.txt').read_bytes()).hexdigest(),'business_source_writes':0}))
