"""Verify downloaded source archives; join split archives without extracting them."""
import hashlib
import json
from pathlib import Path

root = Path(__file__).resolve().parent
manifest = json.loads((root / 'manifest.json').read_text())

def local(name):
    if not isinstance(name, str) or Path(name).name != name or name in ('', '.', '..') or '\\' in name:
        raise ValueError('Unsafe archive filename')
    path = root / name
    if path.is_symlink():
        raise ValueError('Archive symlinks are not accepted')
    return path

for archive in manifest['archives']:
    paths = [local(part['file']) for part in archive['parts']]
    if not all(path.is_file() for path in paths):
        print('Not downloaded:', archive['name'])
        continue
    complete = hashlib.sha256()
    length = 0
    for path, part in zip(paths, archive['parts']):
        digest = hashlib.sha256()
        size = 0
        with path.open('rb') as source:
            for block in iter(lambda: source.read(1024 * 1024), b''):
                digest.update(block)
                complete.update(block)
                size += len(block)
        if size != part['bytes'] or digest.hexdigest() != part['sha256']:
            raise ValueError('Part checksum mismatch: ' + path.name)
        length += size
    if length != archive['bytes'] or complete.hexdigest() != archive['sha256']:
        raise ValueError('Archive checksum mismatch: ' + archive['name'])
    if len(paths) > 1:
        target = local(archive['filename'])
        # Never overwrite an existing local file.
        with target.open('xb') as output:
            for path in paths:
                with path.open('rb') as source:
                    for block in iter(lambda: source.read(1024 * 1024), b''):
                        output.write(block)
    print('Verified:', archive['filename'])
