#!/usr/bin/env python3
"""Create the public corresponding source archive; never include private build state."""
from pathlib import Path
import subprocess
import tarfile
import sys

root = Path(__file__).resolve().parents[1]
out = root / 'build/public/techtiraz-apps-1.0.0.tar.gz'
check_only = sys.argv[1:] == ['--check']
if sys.argv[1:] not in ([], ['--check']):
    raise SystemExit('Usage: techtiraz-source [--check]')
if out.exists() and not check_only:
    raise SystemExit('Refusing to overwrite immutable source archive')
tracked = subprocess.check_output(['git', '-C', str(root), 'ls-files', '--recurse-submodules', '-z']).decode().split('\0')
files = []
aliases = {}
allowed_aliases = {'app/src/main/res/values-in': 'values-id',
                   'app/src/main/res/values-iw': 'values-he'}
for name in filter(None, tracked):
    path = Path(name)
    if (any(p in {'.git', '.local', '.private', '.gradle', 'build', 'creds'} for p in path.parts)
        or path.name in {'local.properties', '.env', 'key.properties', 'signing.key', 'credentials.json'}
        or path.name.startswith('.env.')
        or path.suffix.lower() in {'.jks', '.p12', '.pfx', '.keystore', '.apk'}
        or 'password' in path.name.lower()):
        raise SystemExit('Private/artifact path present in tracked source; archive refused')
    source = root / path
    if source.is_symlink():
        if name not in allowed_aliases or str(source.readlink()) != allowed_aliases[name]:
            raise SystemExit('Unexpected source symlink; archive refused')
        target = source.resolve().relative_to(root)
        if not source.is_dir():
            raise SystemExit('Locale alias target missing; archive refused')
        aliases[name] = str(target)
        continue
    if not source.is_file():
        raise SystemExit('Unexpected non-file; archive refused')
    if source.stat().st_nlink != 1:
        raise SystemExit('Unexpected source hardlink; archive refused')
    private_headers = [b'-----BEGIN ' + kind + b'PRIVATE KEY-----'
                       for kind in [b'', b'RSA ', b'EC ', b'OPENSSH ', b'ENCRYPTED ']]
    content = source.read_bytes()
    if any(header in content for header in private_headers):
        raise SystemExit('Private key header in source; review required')
    files.append((source, 'techtiraz-apps-1.0.0/' + name))
# Materialize only the two essential upstream locale aliases from already audited
# tracked target files. Public tar contains regular files only, no links.
original_files = list(files)
for alias, target in aliases.items():
    target_prefix = 'techtiraz-apps-1.0.0/' + target + '/'
    copied = 0
    for source, name in original_files:
        if name.startswith(target_prefix):
            files.append((source, 'techtiraz-apps-1.0.0/' + alias + '/' + name[len(target_prefix):]))
            copied += 1
    if not copied:
        raise SystemExit('Locale alias has no tracked target files; archive refused')
if not any(name.endswith('/PROVENANCE.md') for _, name in files):
    raise SystemExit('Commit provenance before creating source archive')
if check_only:
    print(f'Public source allowlist: {len(files)} files checked')
    raise SystemExit(0)
out.parent.mkdir(parents=True, exist_ok=True)
with out.open('xb') as handle:
    with tarfile.open(fileobj=handle, mode='w:gz', format=tarfile.PAX_FORMAT) as archive:
        for source, name in sorted(files, key=lambda pair: pair[1]):
            info = archive.gettarinfo(str(source), arcname=name)
            info.type = tarfile.REGTYPE
            info.linkname = ''
            info.size = source.stat().st_size
            with source.open('rb') as content:
                archive.addfile(info, content)
print(f'{out}: {len(files)} source files')
