#!/usr/bin/env python3
"""Nur einen bestehenden Tag und Nachweise aus einer Origin-Revision verwenden."""
import os
from pathlib import Path
import re
import subprocess
import tempfile
import distribution as dist
import release

tag, evidence_revision = os.environ['TB_TAG'], os.environ['TB_EVIDENCE_REVISION']
dist.require(re.fullmatch(r'v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?', tag), 'Ungültiger Tag')
dist.require(re.fullmatch('[0-9a-f]{40}', evidence_revision), 'Ungültige Nachweisrevision')
revision = subprocess.check_output(['git', 'rev-parse', '--verify', tag + '^{commit}'], text=True).strip()
api = release.Gitea()
info = api.request('GET', '/git/commits/' + evidence_revision)
dist.require(info['sha'] == evidence_revision, 'Nachweise nicht am Origin')
# Checkout enthält alle Origin-Branches. Ein nicht vorhandener Commit scheitert hier.
base = f'release-evidence/{tag}'
names = subprocess.check_output(['git', 'ls-tree', '-r', '--name-only', evidence_revision, base], text=True).splitlines()
with tempfile.TemporaryDirectory(prefix='tb-release-') as tmp:
    evidence = Path(tmp) / 'evidence'; evidence.mkdir()
    for name in names:
        relative = Path(name).relative_to(base)
        dist.require('..' not in relative.parts and not relative.is_absolute(), 'Ungültiger Nachweispfad')
        path = evidence / relative; path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(subprocess.check_output(['git', 'show', evidence_revision + ':' + name]))
    packages = Path(tmp) / 'packages'; packages.mkdir()
    draft = api.request('GET', '/releases/tags/' + tag)
    wanted = release.expected(tag[1:])
    dist.require(draft['draft'] and len(draft.get('assets', [])) == len(wanted) and
                 {a['name'] for a in draft['assets']} == set(wanted), 'Unvollständiger Entwurf')
    for asset in draft['assets']:
        (packages / asset['name']).write_bytes(api.download(asset))
    # Grundabnahme kommt aus dem ursprünglichen Taglauf, nicht aus manuell ersetzten Angaben.
    (evidence / 'acceptance.json').write_bytes((packages / 'acceptance.json').read_bytes())
    release.publish(api, packages, evidence, tag, revision)
