#!/usr/bin/env python3
"""Verify published archive bytes and membership, not mathematical truth."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import zipfile


def need(ok, message):
    if not ok:
        raise ValueError(message)


def verify(path):
    with zipfile.ZipFile(path) as archive:
        names = archive.namelist()
        need(len(names) == len(set(names)), 'Duplicate ZIP member')
        need('ARCHIVE_MANIFEST.json' in names, 'Missing archive manifest')
        manifest = json.loads(archive.read('ARCHIVE_MANIFEST.json'))
        need(manifest['format'] == 'PHI-publication-archive-v1', 'Unknown manifest format')
        rows = manifest['files']
        expected = [row['path'] for row in rows]
        need(len(expected) == len(set(expected)), 'Duplicate manifest member')
        need(set(names) == set(expected) | {'ARCHIVE_MANIFEST.json'}, 'Wrong archive membership')
        total = 0
        for row in rows:
            name = row['path']
            parsed = PurePosixPath(name)
            need(name == parsed.as_posix() and not parsed.is_absolute() and '..' not in parsed.parts,
                 'Unsafe archive path: ' + name)
            info = archive.getinfo(name)
            need(not info.is_dir() and (info.external_attr >> 16) & 0o170000 != 0o120000,
                 'Directory or symlink member: ' + name)
            need(type(row['bytes']) is int and row['bytes'] >= 0 and info.file_size == row['bytes'],
                 'Wrong member size: ' + name)
            digest = hashlib.sha256()
            with archive.open(name) as source:
                while block := source.read(1024 * 1024):
                    digest.update(block)
            need(digest.hexdigest() == row['sha256'], 'Changed archive bytes: ' + name)
            total += row['bytes']
        return {'passed': True, 'scope': 'Archive integrity only; no proof compiler or kernel ran.',
                'archive': Path(path).name, 'files': len(rows), 'uncompressed_bytes': total,
                'archive_sha256': file_sha(path), 'kind': manifest['kind']}


def file_sha(path):
    digest = hashlib.sha256()
    with open(path, 'rb') as source:
        while block := source.read(1024 * 1024):
            digest.update(block)
    return digest.hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('archives', nargs='+', type=Path)
    args = parser.parse_args()
    for path in args.archives:
        print(json.dumps(verify(path), sort_keys=True))


if __name__ == '__main__':
    main()
