#!/usr/bin/env python3
"""Verify and join the source parts in the current folder. Never extracts ZIPs."""
from pathlib import Path
import hashlib
import json
import os
import re
import sys

MANIFEST = 'source-manifest.json'
PART_BYTES = 20 * 1024 * 1024
MAX_PARTS = 1024
BLOCK = 1024 * 1024

def plain_name(value):
    if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,199}', value):
        raise ValueError('Unsafe filename in manifest')
    if '..' in value or value.endswith('.'):
        raise ValueError('Unsafe filename in manifest')
    stem = value.split('.', 1)[0].upper()
    if stem in {'CON','PRN','AUX','NUL'} or re.fullmatch(r'(COM|LPT)[1-9]', stem):
        raise ValueError('Reserved device filename in manifest')
    return value

def child(base, name, required=False):
    name = plain_name(name)
    p = base / name
    if p.is_symlink():
        raise ValueError('Symbolic links are not accepted: ' + name)
    try:
        p.resolve().relative_to(base)
    except ValueError:
        raise ValueError('Path escapes the current folder: ' + name)
    if required and not p.is_file():
        raise ValueError('Missing regular file: ' + name)
    return p

def number(value, limit):
    if type(value) is not int or value < 1 or value > limit:
        raise ValueError('Invalid byte count in manifest')
    return value

def digest(value):
    if not isinstance(value, str) or not re.fullmatch(r'[a-fA-F0-9]{64}', value):
        raise ValueError('Invalid SHA-256 in manifest')
    return value.lower()

def hash_file(p):
    h = hashlib.sha256(); count = 0
    with p.open('rb') as source:
        while True:
            data = source.read(BLOCK)
            if not data: break
            h.update(data); count += len(data)
    return count, h.hexdigest()

def load(base):
    manifest_path = child(base, MANIFEST, required=True)
    if manifest_path.stat().st_size > 1024 * 1024:
        raise ValueError('Manifest exceeds the supported size')
    def unique_object(pairs):
        value = {}
        for key, item in pairs:
            if key in value: raise ValueError('Duplicate JSON key in manifest')
            value[key] = item
        return value
    m = json.loads(manifest_path.read_text(encoding='utf-8'), object_pairs_hook=unique_object)
    if not isinstance(m, dict) or m.get('format') != 'burg-source-parts-v1' or m.get('version_name') != '0.2.0-alpha02' or type(m.get('version_code')) is not int or m.get('version_code') != 2:
        raise ValueError('Unsupported source manifest/version')
    if type(m.get('part_bytes')) is not int or m.get('part_bytes') != PART_BYTES:
        raise ValueError('Unexpected part size')
    full = m.get('full_zip', {})
    if not isinstance(full, dict):
        raise ValueError('Invalid final ZIP metadata')
    name = plain_name(full.get('name'))
    if not name.endswith('.zip'):
        raise ValueError('Final filename must be a ZIP filename')
    total = number(full.get('bytes'), MAX_PARTS * PART_BYTES)
    full_sha = digest(full.get('sha256'))
    parts = m.get('parts')
    if not isinstance(parts, list) or not 1 <= len(parts) <= MAX_PARTS:
        raise ValueError('Invalid part count')
    seen = set(); checked = []; summed = 0
    prefix = 'BurgBrowser-0.2.0-alpha02-source.zip.part'
    for index, item in enumerate(parts, 1):
        if not isinstance(item, dict): raise ValueError('Invalid part metadata')
        part_name = plain_name(item.get('name'))
        if type(item.get('order')) is not int or item['order'] != index or part_name != prefix + str(index).zfill(2):
            raise ValueError('Parts must have consecutive names and order')
        if part_name in seen:
            raise ValueError('Duplicate part filename')
        seen.add(part_name)
        size = number(item.get('bytes'), PART_BYTES)
        if index < len(parts) and size != PART_BYTES:
            raise ValueError('Only the last part may be shorter than 20 MiB')
        checked.append((part_name, size, digest(item.get('sha256')))); summed += size
    if summed != total or name in seen or name in {MANIFEST,'join-source.py','SHA256SUMS','README-DE.txt','README-EN.txt'}:
        raise ValueError('Conflicting output name or incorrect total byte count')
    return name, total, full_sha, checked

def main():
    if len(sys.argv) != 1:
        raise ValueError('Run without arguments in the folder containing all parts and the manifest')
    base = Path.cwd().resolve()
    name, total, expected_sha, parts = load(base)
    target = child(base, name)
    temporary = child(base, name + '.part')
    if target.exists() or temporary.exists():
        raise ValueError('Refusing to overwrite the final ZIP or an existing .part file')
    # All source sizes and hashes are verified before creating any output file.
    for part_name, size, expected in parts:
        part = child(base, part_name, required=True)
        if part.stat().st_size != size or hash_file(part) != (size, expected):
            raise ValueError('Part size/SHA-256 mismatch: ' + part_name)
    created = False
    try:
        full_hash = hashlib.sha256(); full_count = 0
        with temporary.open('xb') as destination:
            created = True
            for part_name, expected_size, expected in parts:
                part = child(base, part_name, required=True)
                part_hash = hashlib.sha256(); count = 0
                with part.open('rb') as source:
                    while True:
                        data = source.read(BLOCK)
                        if not data: break
                        destination.write(data); part_hash.update(data); full_hash.update(data)
                        count += len(data); full_count += len(data)
                # Recheck each input during copying, guarding changes after preflight.
                if count != expected_size or part_hash.hexdigest() != expected:
                    raise ValueError('Part changed while joining: ' + part_name)
            destination.flush(); os.fsync(destination.fileno())
        if full_count != total or full_hash.hexdigest() != expected_sha:
            raise ValueError('Final ZIP size/SHA-256 mismatch')
        # Atomic no-clobber publication: POSIX rename/replace could overwrite an
        # existing target. A same-folder hard link fails if target already exists.
        # No unsafe fallback is used on filesystems without hard-link support.
        os.link(str(temporary), str(target))
        temporary.unlink(); created = False
        print('Verified ZIP created: ' + name)
        print('SHA-256: ' + expected_sha)
        print('Nothing was extracted or executed.')
    finally:
        if created:
            try: temporary.unlink()
            except FileNotFoundError: pass

if __name__ == '__main__':
    try: main()
    except (ValueError, OSError, KeyError, TypeError, json.JSONDecodeError) as error:
        print('Cannot join source package: ' + str(error), file=sys.stderr)
        sys.exit(1)
