#!/usr/bin/env python3
"""Verify all indexed source parts, then reassemble the original source archive."""
import argparse,hashlib,json,os,tempfile
from pathlib import Path

def reassemble(directory:Path,destination:Path):
    manifest=json.loads((directory/'source-manifest.json').read_text())
    if manifest.get('format')!=1 or not manifest.get('parts'):raise ValueError('Invalid source manifest')
    if destination.exists():raise ValueError('Destination exists; choose a new file')
    total=0;whole=hashlib.sha256();seen=set()
    with tempfile.NamedTemporaryFile(dir=destination.parent)as out:
        for part in manifest['parts']:
            name=part['filename']
            if Path(name).name!=name or '\\'in name or name in seen:raise ValueError('Unsafe/duplicate part name')
            seen.add(name);path=directory/name
            if path.is_symlink():raise ValueError('Source part is a symlink')
            data=path.read_bytes()
            if len(data)!=part['size']or hashlib.sha256(data).hexdigest()!=part['sha256']:raise ValueError('Source part checksum mismatch')
            out.write(data);whole.update(data);total+=len(data)
        if total!=manifest['size']or whole.hexdigest()!=manifest['sha256']:raise ValueError('Source archive checksum mismatch')
        out.flush()
        # Hard-link publishes only if the chosen path is still absent.
        os.link(out.name,destination)
    return whole.hexdigest()

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('directory',type=Path);p.add_argument('destination',type=Path);a=p.parse_args()
    try:print(reassemble(a.directory,a.destination))
    except (OSError,ValueError,KeyError)as e:raise SystemExit('Reassembly refused: '+str(e))
