#!/usr/bin/env python3
"""Verify all issued package bytes. Run after extraction; Python stdlib only."""
import hashlib
import json
from pathlib import Path
import sys

root = Path(__file__).resolve().parent
manifest = json.loads((root / 'MANIFEST.json').read_text())
errors = []
for item in manifest['files']:
    rel = Path(item['path'])
    if rel.is_absolute() or '..' in rel.parts:
        errors.append('Unsafe manifest path: '+str(rel))
        continue
    p = root / rel
    if not p.is_file():
        errors.append('Missing: '+str(rel))
        continue
    data = p.read_bytes()
    if len(data) != item['bytes'] or hashlib.sha256(data).hexdigest() != item['sha256']:
        errors.append('Changed: '+str(rel))
listed = {i['path'] for i in manifest['files']}
extras = [str(p.relative_to(root)) for p in root.rglob('*')
          if p.is_file() and p.name != 'MANIFEST.json'
          and str(p.relative_to(root)) not in listed]
print(json.dumps({'checked_files':len(listed), 'errors':errors,
                  'unlisted_files':extras, 'status':'PASS' if not errors and not extras else 'FAIL'}, indent=2))
sys.exit(1 if errors or extras else 0)
