#!/usr/bin/env python3

from __future__ import annotations

import argparse
import hashlib
import json
import os
import shlex
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any


PROJECT_ROOT = Path(
    os.environ.get(
        "FIVEBR_INFRA_ROOT",
        "/opt/5ibr-infra",
    )
)

VERSION_PATH = PROJECT_ROOT / "VERSION"

DEFAULT_RELEASE_ENV = Path(
    os.environ.get(
        "FIVEBR_RELEASE_ENV",
        "/opt/5ibr-release/release.env",
    )
)

REQUIRED_CONFIG_KEYS = (
    "FIVEBR_PROJECT_ROOT",
    "FIVEBR_RELEASE_ROOT",
    "FIVEBR_BUILD_DIR",
    "FIVEBR_REPOSITORY_DIR",
    "FIVEBR_ARTIFACTS_DIR",
    "FIVEBR_LOG_DIR",
    "FIVEBR_SIGNING_HOME",
    "FIVEBR_APT_HOST",
    "FIVEBR_APT_SSH_PORT",
    "FIVEBR_APT_REMOTE_ROOT",
    "FIVEBR_APT_SIGNING_FINGERPRINT",
)


class ReleaseError(RuntimeError):
    pass


def read_version() -> str:
    if not VERSION_PATH.is_file():
        raise ReleaseError(
            f"VERSION file not found: {VERSION_PATH}"
        )

    version = VERSION_PATH.read_text(
        encoding="utf-8"
    ).strip()

    if not version:
        raise ReleaseError(
            "VERSION file is empty"
        )

    return version


def run_git(
    *arguments: str,
) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [
            "git",
            *arguments,
        ],
        cwd=PROJECT_ROOT,
        check=False,
        capture_output=True,
        text=True,
    )


def current_branch() -> str:
    result = run_git(
        "branch",
        "--show-current",
    )

    if result.returncode != 0:
        raise ReleaseError(
            result.stderr.strip()
            or "unable to determine Git branch"
        )

    return result.stdout.strip()


def worktree_clean() -> bool:
    result = run_git(
        "status",
        "--short",
    )

    if result.returncode != 0:
        raise ReleaseError(
            result.stderr.strip()
            or "unable to inspect Git worktree"
        )

    return not result.stdout.strip()


def parse_release_env(
    path: Path,
) -> dict[str, str]:
    if not path.is_file():
        raise ReleaseError(
            f"release config not found: {path}"
        )

    values: dict[str, str] = {}

    for line_number, raw_line in enumerate(
        path.read_text(
            encoding="utf-8"
        ).splitlines(),
        start=1,
    ):
        line = raw_line.strip()

        if not line or line.startswith("#"):
            continue

        if "=" not in line:
            raise ReleaseError(
                "invalid release config line "
                f"{line_number}: missing '='"
            )

        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip()

        if not key:
            raise ReleaseError(
                "invalid release config line "
                f"{line_number}: empty key"
            )

        if key in values:
            raise ReleaseError(
                f"duplicate release config key: {key}"
            )

        values[key] = value

    missing = [
        key
        for key in REQUIRED_CONFIG_KEYS
        if not values.get(key)
    ]

    if missing:
        raise ReleaseError(
            "missing release config keys: "
            + ", ".join(missing)
        )

    return values


def validate_config(
    path: Path,
) -> dict[str, Any]:
    values = parse_release_env(path)

    configured_project = Path(
        values["FIVEBR_PROJECT_ROOT"]
    ).resolve()

    if configured_project != PROJECT_ROOT.resolve():
        raise ReleaseError(
            "configured project root does not match "
            f"runtime project root: {configured_project}"
        )

    signing_home = Path(
        values["FIVEBR_SIGNING_HOME"]
    )

    if not signing_home.is_dir():
        raise ReleaseError(
            f"signing home not found: {signing_home}"
        )

    ssh_port = values[
        "FIVEBR_APT_SSH_PORT"
    ]

    if not ssh_port.isdigit():
        raise ReleaseError(
            "FIVEBR_APT_SSH_PORT must be numeric"
        )

    fingerprint = values[
        "FIVEBR_APT_SIGNING_FINGERPRINT"
    ]

    if (
        len(fingerprint) != 40
        or any(
            character not in "0123456789ABCDEFabcdef"
            for character in fingerprint
        )
    ):
        raise ReleaseError(
            "invalid APT signing fingerprint"
        )

    return {
        "valid": True,
        "version": read_version(),
        "release_env": str(path),
        "project_root": str(PROJECT_ROOT),
        "signing_home": str(signing_home),
        "apt_host": values["FIVEBR_APT_HOST"],
        "apt_ssh_port": int(ssh_port),
        "apt_remote_root": values[
            "FIVEBR_APT_REMOTE_ROOT"
        ],
        "signing_fingerprint": fingerprint.upper(),
    }


def status_payload() -> dict[str, Any]:
    return {
        "project_root": str(PROJECT_ROOT),
        "version": read_version(),
        "branch": current_branch(),
        "worktree_clean": worktree_clean(),
        "release_env": str(DEFAULT_RELEASE_ENV),
    }


def validate_release_tag_syntax(
    tag: str,
) -> str:
    if not tag.startswith("v"):
        raise ReleaseError(
            f"release tag is invalid: {tag}"
        )

    parts = tag[1:].split(".")

    if len(parts) != 3:
        raise ReleaseError(
            f"release tag is invalid: {tag}"
        )

    for part in parts:
        if not part.isdigit():
            raise ReleaseError(
                f"release tag is invalid: {tag}"
            )

        if len(part) > 1 and part.startswith("0"):
            raise ReleaseError(
                f"release tag is invalid: {tag}"
            )

    return tag


def validate_release_tag(
    tag: str | None,
) -> str | None:
    if tag is None:
        return None

    expected = f"v{read_version()}"

    if tag != expected:
        raise ReleaseError(
            "tag version does not match VERSION: "
            f"expected {expected}, got {tag}"
        )

    return tag


def build_dry_run_payload(
    tag: str | None = None,
) -> dict[str, Any]:
    validated_tag = validate_release_tag(tag)

    return {
        "dry_run": True,
        "version": read_version(),
        "tag": validated_tag,
        "steps": [
            "run-tests",
            "build-deb",
            "build-apt-repository",
            "verify-signatures",
            "archive-artifacts",
        ],
    }


def run_command(
    arguments: list[str],
    *,
    cwd: Path = PROJECT_ROOT,
    environment: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
    command_environment = {
        **os.environ,
        **(environment or {}),
    }

    result = subprocess.run(
        arguments,
        cwd=cwd,
        env=command_environment,
        check=False,
        capture_output=True,
        text=True,
    )

    if result.returncode != 0:
        command = " ".join(arguments)
        detail = (
            result.stderr.strip()
            or result.stdout.strip()
            or f"exit code {result.returncode}"
        )
        raise ReleaseError(
            f"command failed: {command}: {detail}"
        )

    return result


def configured_path(
    values: dict[str, str],
    key: str,
) -> Path:
    return Path(values[key]).expanduser().resolve()


def require_under_root(
    candidate: Path,
    root: Path,
    description: str,
) -> None:
    try:
        candidate.relative_to(root)
    except ValueError as exc:
        raise ReleaseError(
            f"{description} is outside release root: "
            f"{candidate}"
        ) from exc


def clean_directory(
    directory: Path,
    *,
    release_root: Path,
) -> None:
    require_under_root(
        directory,
        release_root,
        "output directory",
    )

    if directory == release_root:
        raise ReleaseError(
            "refusing to clean the release root itself"
        )

    if directory.exists():
        shutil.rmtree(directory)

    directory.mkdir(
        parents=True,
        exist_ok=True,
    )


def file_sha256(path: Path) -> str:
    digest = hashlib.sha256()

    with path.open("rb") as handle:
        for block in iter(
            lambda: handle.read(1024 * 1024),
            b"",
        ):
            digest.update(block)

    return digest.hexdigest()


def source_date_epoch(
    tag: str | None,
) -> str:
    reference = (
        f"{tag}^{{commit}}"
        if tag is not None
        else "HEAD"
    )

    result = run_git(
        "show",
        "-s",
        "--format=%ct",
        reference,
    )

    if result.returncode != 0:
        raise ReleaseError(
            result.stderr.strip()
            or f"unable to read timestamp for {reference}"
        )

    epoch = result.stdout.strip()

    if not epoch.isdigit():
        raise ReleaseError(
            f"invalid source date epoch: {epoch!r}"
        )

    return epoch


def execute_local_build(
    tag: str | None,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    validated_tag = validate_release_tag(tag)
    config_summary = validate_config(
        DEFAULT_RELEASE_ENV
    )
    values = parse_release_env(
        DEFAULT_RELEASE_ENV
    )

    version = read_version()
    release_root = configured_path(
        values,
        "FIVEBR_RELEASE_ROOT",
    )
    repository_dir = configured_path(
        values,
        "FIVEBR_REPOSITORY_DIR",
    )
    artifacts_dir = configured_path(
        values,
        "FIVEBR_ARTIFACTS_DIR",
    )
    signing_home = configured_path(
        values,
        "FIVEBR_SIGNING_HOME",
    )

    for directory, description in (
        (repository_dir, "repository directory"),
        (artifacts_dir, "artifacts directory"),
        (signing_home, "signing home"),
    ):
        require_under_root(
            directory,
            release_root,
            description,
        )

    if not signing_home.is_dir():
        raise ReleaseError(
            f"signing home not found: {signing_home}"
        )

    build_deb = (
        PROJECT_ROOT
        / "packaging"
        / "scripts"
        / "build-deb"
    )
    build_apt = (
        PROJECT_ROOT
        / "packaging"
        / "scripts"
        / "build-apt-repository"
    )

    for executable in (
        build_deb,
        build_apt,
    ):
        if not executable.is_file():
            raise ReleaseError(
                f"required build tool not found: {executable}"
            )

    skip_tests = (
        os.environ.get(
            "FIVEBR_RELEASE_SKIP_TESTS"
        )
        == "1"
    )
    skip_signature_verify = (
        os.environ.get(
            "FIVEBR_RELEASE_SKIP_SIGNATURE_VERIFY"
        )
        == "1"
    )
    skip_package_verify = (
        os.environ.get(
            "FIVEBR_RELEASE_SKIP_PACKAGE_VERIFY"
        )
        == "1"
    )

    if not skip_tests:
        run_command(
            [
                sys.executable,
                "-m",
                "pytest",
                "-q",
            ]
        )

    dist_dir = PROJECT_ROOT / "dist"

    if dist_dir.exists():
        shutil.rmtree(dist_dir)

    run_command(
        [str(build_deb)]
    )

    package = (
        dist_dir
        / f"5ibr-infra_{version}_all.deb"
    )

    if not package.is_file() or package.stat().st_size == 0:
        raise ReleaseError(
            f"expected Debian package not found: {package}"
        )

    if not skip_package_verify:
        expected_fields = {
            "Package": "5ibr-infra",
            "Version": version,
            "Architecture": "all",
        }

        for field, expected in expected_fields.items():
            result = run_command(
                [
                    "dpkg-deb",
                    "--field",
                    str(package),
                    field,
                ]
            )

            actual = result.stdout.strip()

            if actual != expected:
                raise ReleaseError(
                    f"invalid package {field}: "
                    f"expected {expected!r}, got {actual!r}"
                )

    clean_directory(
        repository_dir,
        release_root=release_root,
    )

    artifacts_dir.mkdir(
        parents=True,
        exist_ok=True,
    )

    epoch = source_date_epoch(
        validated_tag
    )

    run_command(
        [
            str(build_apt),
            "--package",
            str(package),
            "--output",
            str(repository_dir),
            "--version-file",
            str(VERSION_PATH),
            "--gnupg-home",
            str(signing_home),
            "--signing-key",
            values[
                "FIVEBR_APT_SIGNING_FINGERPRINT"
            ],
            "--export-public-key",
        ],
        environment={
            "SOURCE_DATE_EPOCH": epoch,
        },
    )

    required_files = (
        "5ibr-archive-keyring.gpg",
        "dists/stable/Release",
        "dists/stable/Release.gpg",
        "dists/stable/InRelease",
        "dists/stable/main/binary-all/Packages",
        "dists/stable/main/binary-all/Packages.gz",
        (
            "pool/main/5/5ibr-infra/"
            f"5ibr-infra_{version}_all.deb"
        ),
    )

    for relative in required_files:
        output = repository_dir / relative

        if not output.is_file() or output.stat().st_size == 0:
            raise ReleaseError(
                f"required repository file missing: {relative}"
            )

    if not skip_signature_verify:
        keyring = (
            repository_dir
            / "5ibr-archive-keyring.gpg"
        )
        release = (
            repository_dir
            / "dists"
            / "stable"
            / "Release"
        )
        release_signature = release.with_name(
            "Release.gpg"
        )
        inrelease = release.with_name(
            "InRelease"
        )

        run_command(
            [
                "gpgv",
                "--keyring",
                str(keyring),
                str(release_signature),
                str(release),
            ]
        )

        run_command(
            [
                "gpgv",
                "--keyring",
                str(keyring),
                str(inrelease),
            ]
        )

    if not skip_package_verify:
        packages = (
            repository_dir
            / "dists"
            / "stable"
            / "main"
            / "binary-all"
            / "Packages"
        )
        packages_gzip = packages.with_suffix(
            ".gz"
        )

        gzip_result = run_command(
            [
                "gzip",
                "-cd",
                str(packages_gzip),
            ]
        )

        if (
            gzip_result.stdout.encode("utf-8")
            != packages.read_bytes()
        ):
            raise ReleaseError(
                "Packages.gz does not match Packages"
            )

        packages_text = packages.read_text(
            encoding="utf-8"
        )

        if f"Version: {version}" not in packages_text:
            raise ReleaseError(
                "package index does not contain "
                f"version {version}"
            )

    archived_package = (
        artifacts_dir / package.name
    )
    shutil.copy2(
        package,
        archived_package,
    )

    checksum_path = archived_package.with_suffix(
        archived_package.suffix + ".sha256"
    )
    checksum_path.write_text(
        (
            f"{file_sha256(archived_package)}  "
            f"{archived_package.name}\n"
        ),
        encoding="utf-8",
    )

    return {
        "built": True,
        "version": version,
        "tag": validated_tag,
        "source_date_epoch": epoch,
        "package": str(archived_package),
        "checksum": str(checksum_path),
        "repository": str(repository_dir),
        "release_env": config_summary[
            "release_env"
        ],
        "published": False,
    }


def validate_build_execution(
    tag: str | None,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    validated_tag = validate_release_tag(tag)
    config = validate_config(DEFAULT_RELEASE_ENV)

    return {
        "execute": True,
        "ready": True,
        "version": read_version(),
        "tag": validated_tag,
        "release_env": config["release_env"],
        "steps": [
            "run-tests",
            "build-deb",
            "build-apt-repository",
            "verify-signatures",
            "archive-artifacts",
        ],
    }


def repository_required_files(
    version: str,
) -> tuple[str, ...]:
    return (
        "5ibr-archive-keyring.gpg",
        "dists/stable/Release",
        "dists/stable/Release.gpg",
        "dists/stable/InRelease",
        "dists/stable/main/binary-all/Packages",
        "dists/stable/main/binary-all/Packages.gz",
        (
            "pool/main/5/5ibr-infra/"
            f"5ibr-infra_{version}_all.deb"
        ),
    )


def validate_local_repository(
    repository_dir: Path,
    version: str,
) -> None:
    missing = []

    for relative in repository_required_files(
        version
    ):
        path = repository_dir / relative

        if not path.is_file() or path.stat().st_size == 0:
            missing.append(relative)

    if missing:
        raise ReleaseError(
            "local repository is incomplete: "
            + ", ".join(missing)
        )


def stage_dry_run_payload(
    tag: str | None,
) -> dict[str, Any]:
    validated_tag = validate_release_tag(tag)
    version = read_version()

    # Dry-run must remain usable in CI and development
    # environments where the production release config
    # intentionally does not exist.
    remote_root = os.environ.get(
        "FIVEBR_APT_REMOTE_ROOT",
        "/var/www/apt",
    ).rstrip("/")

    if not remote_root:
        raise ReleaseError(
            "FIVEBR_APT_REMOTE_ROOT must not be empty"
        )

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    return {
        "dry_run": True,
        "version": version,
        "tag": validated_tag,
        "remote_target": (
            f"{remote_root}/incoming/{release_name}"
        ),
        "steps": [
            "validate-local-repository",
            "check-remote-target",
            "create-remote-staging",
            "rsync-repository",
            "verify-remote-files",
        ],
        "promoted": False,
    }


def execute_stage(
    tag: str | None,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    validated_tag = validate_release_tag(tag)
    version = read_version()
    values = parse_release_env(
        DEFAULT_RELEASE_ENV
    )
    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    release_root = configured_path(
        values,
        "FIVEBR_RELEASE_ROOT",
    )
    repository_dir = configured_path(
        values,
        "FIVEBR_REPOSITORY_DIR",
    )

    require_under_root(
        repository_dir,
        release_root,
        "repository directory",
    )

    validate_local_repository(
        repository_dir,
        version,
    )

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    remote_root = values[
        "FIVEBR_APT_REMOTE_ROOT"
    ]
    remote_target = (
        f"{remote_root}/incoming/{release_name}"
    )

    ssh_alias = os.environ.get(
        "FIVEBR_APT_SSH_ALIAS",
        "apt-vps",
    )

    check_result = subprocess.run(
        [
            "ssh",
            ssh_alias,
            (
                "set -eu; "
                f"target={remote_target!r}; "
                'if test -e "$target"; then '
                'echo "remote target already exists: '
                '$target" >&2; exit 2; fi'
            ),
        ],
        cwd=PROJECT_ROOT,
        check=False,
        capture_output=True,
        text=True,
    )

    if check_result.returncode != 0:
        detail = (
            check_result.stderr.strip()
            or check_result.stdout.strip()
            or (
                "unable to verify remote staging "
                f"target: {remote_target}"
            )
        )
        raise ReleaseError(detail)

    run_command(
        [
            "ssh",
            ssh_alias,
            (
                "install -d -m 0750 "
                f"{remote_target!r}"
            ),
        ]
    )

    run_command(
        [
            "rsync",
            "-ah",
            "--delete",
            "--itemize-changes",
            "-e",
            "ssh",
            f"{repository_dir}/",
            f"{ssh_alias}:{remote_target}/",
        ]
    )

    required = " ".join(
        repository_required_files(version)
    )

    verify_script = (
        "set -eu; "
        f"target={remote_target!r}; "
        f"for relative in {required}; do "
        'test -s "$target/$relative"; '
        "done; "
        'grep -F '
        f"{('Version: ' + version)!r} "
        '"$target/dists/stable/main/'
        'binary-all/Packages"'
    )

    run_command(
        [
            "ssh",
            ssh_alias,
            verify_script,
        ]
    )

    return {
        "staged": True,
        "version": version,
        "tag": validated_tag,
        "remote_target": remote_target,
        "repository": str(repository_dir),
        "apt_host": config["apt_host"],
        "promoted": False,
    }


def promote_dry_run_payload(
    tag: str | None,
) -> dict[str, Any]:
    validated_tag = validate_release_tag(tag)
    version = read_version()

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    return {
        "dry_run": True,
        "version": version,
        "tag": validated_tag,
        "release": release_name,
        "command": (
            "sudo /usr/local/sbin/"
            f"5ibr-apt-promote {release_name}"
        ),
        "steps": [
            "validate-clean-worktree",
            "validate-release-config",
            "verify-remote-staging",
            "run-restricted-promote-command",
            "verify-current-link",
            "verify-previous-link",
        ],
    }


def execute_promote(
    tag: str | None,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    validated_tag = validate_release_tag(tag)
    version = read_version()

    values = parse_release_env(
        DEFAULT_RELEASE_ENV
    )
    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    remote_root = values[
        "FIVEBR_APT_REMOTE_ROOT"
    ]
    staged_path = (
        f"{remote_root}/incoming/{release_name}"
    )

    ssh_alias = os.environ.get(
        "FIVEBR_APT_SSH_ALIAS",
        "apt-vps",
    )

    staged_check = subprocess.run(
        [
            "ssh",
            ssh_alias,
            f"test -d {staged_path!r}",
        ],
        cwd=PROJECT_ROOT,
        check=False,
        capture_output=True,
        text=True,
    )

    if staged_check.returncode != 0:
        raise ReleaseError(
            "staged release not found: "
            f"{staged_path}"
        )

    promote_result = run_command(
        [
            "ssh",
            ssh_alias,
            (
                "sudo /usr/local/sbin/"
                f"5ibr-apt-promote {release_name}"
            ),
        ]
    )

    verify_command = (
        'printf "CURRENT=%s\n" '
        '"$(readlink /var/www/apt/current)"; '
        'printf "PREVIOUS=%s\n" '
        '"$(readlink /var/www/apt/previous)"'
    )

    verify_result = run_command(
        [
            "ssh",
            ssh_alias,
            verify_command,
        ]
    )

    links: dict[str, str] = {}

    for line in verify_result.stdout.splitlines():
        if "=" not in line:
            continue

        key, value = line.split("=", 1)
        links[key] = value

    expected_current = (
        f"releases/{release_name}"
    )

    current = links.get("CURRENT", "")
    previous = links.get("PREVIOUS", "")

    if current != expected_current:
        raise ReleaseError(
            "remote current link mismatch: "
            f"expected {expected_current}, "
            f"got {current or '<empty>'}"
        )

    return {
        "promoted": True,
        "version": version,
        "tag": validated_tag,
        "release": release_name,
        "current": current,
        "previous": previous,
        "apt_host": config["apt_host"],
        "remote_output": (
            promote_result.stdout.strip()
        ),
    }


def validate_promote_execution(
    tag: str | None,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    validated_tag = validate_release_tag(tag)
    version = read_version()

    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    return {
        "execute": True,
        "ready": True,
        "version": version,
        "tag": validated_tag,
        "release": release_name,
        "apt_host": config["apt_host"],
        "command": (
            "sudo /usr/local/sbin/"
            f"5ibr-apt-promote {release_name}"
        ),
        "promoted": False,
    }


def verify_dry_run_payload(
    tag: str | None,
    network_via: str,
) -> dict[str, Any]:
    validated_tag = validate_release_tag(tag)
    version = read_version()

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    return {
        "dry_run": True,
        "version": version,
        "tag": validated_tag,
        "release": release_name,
        "expected_current": (
            f"releases/{release_name}"
        ),
        "network_via": network_via,
        "checks": [
            "verify-current-link",
            "verify-previous-link",
            "verify-https-files",
            "verify-release-date",
            "verify-apt-signature",
            "verify-apt-candidate",
        ],
    }


def execute_remote_network_verify(
    *,
    version: str,
    ssh_alias: str,
    apt_base_url: str,
) -> dict[str, Any]:
    apt_url = shlex.quote(apt_base_url)

    public_paths = (
        "/5ibr-archive-keyring.gpg",
        "/dists/stable/InRelease",
        "/dists/stable/Release",
        "/dists/stable/Release.gpg",
        (
            "/dists/stable/main/"
            "binary-all/Packages"
        ),
        (
            "/dists/stable/main/"
            "binary-all/Packages.gz"
        ),
        (
            "/pool/main/5/5ibr-infra/"
            f"5ibr-infra_{version}_all.deb"
        ),
    )

    path_arguments = " ".join(
        shlex.quote(path)
        for path in public_paths
    )

    https_command = (
        "set -eu; "
        f"apt_url={apt_url}; "
        f"for path in {path_arguments}; do "
        'curl -fsSI "${apt_url}${path}" '
        ">/dev/null; "
        "done"
    )

    run_command(
        [
            "ssh",
            ssh_alias,
            https_command,
        ]
    )

    expected_version = shlex.quote(version)

    apt_command = (
        "set -eu; "
        f"apt_url={apt_url}; "
        f"expected_version={expected_version}; "
        'tmpdir="$(mktemp -d)"; '
        "trap "
        "'find \"$tmpdir\" -depth -delete "
        "2>/dev/null || true' EXIT; "
        'state="$tmpdir/state"; '
        'cache="$tmpdir/cache"; '
        'sources="$tmpdir/5ibr.list"; '
        'keyring="$tmpdir/5ibr-archive-keyring.gpg"; '
        'mkdir -p "$state/lists/partial" '
        '"$cache/archives/partial"; '
        'curl -fsSL '
        '"${apt_url}/5ibr-archive-keyring.gpg" '
        '-o "$keyring"; '
        'test -s "$keyring"; '
        'printf "deb [signed-by=%s] %s stable main\\n" '
        '"$keyring" "$apt_url" > "$sources"; '
        'apt_output="$(apt-get '
        '-o "Dir::State=$state" '
        '-o "Dir::Cache=$cache" '
        '-o "Dir::Etc::sourcelist=$sources" '
        '-o "Dir::Etc::sourceparts=-" '
        '-o "APT::Get::List-Cleanup=0" '
        'update 2>&1)"; '
        'printf "%s\\n" "$apt_output"; '
        'date_warning="Invalid \'Date\' entry"; '
        'if printf "%s\\n" "$apt_output" '
        '| grep -Fq "$date_warning"; '
        "then "
        'echo "invalid Release Date warning" >&2; '
        "exit 1; "
        "fi; "
        'policy="$(apt-cache '
        '-o "Dir::State=$state" '
        '-o "Dir::Cache=$cache" '
        '-o "Dir::Etc::sourcelist=$sources" '
        '-o "Dir::Etc::sourceparts=-" '
        'policy 5ibr-infra)"; '
        'candidate="$(printf "%s\\n" "$policy" '
        "| awk '/Candidate:/ {print $2; exit}')\"; "
        'test "$candidate" = "$expected_version"; '
        'printf "RELEASE_DATE_ACCEPTED=true\\n"; '
        'printf "CANDIDATE=%s\\n" "$candidate"'
    )

    result = run_command(
        [
            "ssh",
            ssh_alias,
            apt_command,
        ]
    )

    values: dict[str, str] = {}

    for line in result.stdout.splitlines():
        if "=" not in line:
            continue

        key, value = line.split("=", 1)

        if key in {
            "RELEASE_DATE_ACCEPTED",
            "CANDIDATE",
        }:
            values[key] = value

    candidate = values.get("CANDIDATE", "")
    date_accepted = (
        values.get("RELEASE_DATE_ACCEPTED")
        == "true"
    )

    if candidate != version:
        raise ReleaseError(
            "APT candidate mismatch: "
            f"expected {version}, "
            f"got {candidate or '<empty>'}"
        )

    if not date_accepted:
        raise ReleaseError(
            "remote APT verification did not "
            "confirm the Release Date"
        )

    return {
        "candidate": candidate,
        "release_date_accepted": True,
    }


def execute_verify(
    tag: str | None,
    network_via: str,
    *,
    allow_historical_release: bool = False,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    if allow_historical_release:
        if tag is None:
            raise ReleaseError(
                "historical verification requires "
                "an explicit release tag"
            )

        validated_tag = (
            validate_release_tag_syntax(tag)
        )
        version = validated_tag.removeprefix("v")
    else:
        validated_tag = validate_release_tag(tag)
        version = read_version()

    values = parse_release_env(
        DEFAULT_RELEASE_ENV
    )
    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    expected_current = (
        f"releases/{release_name}"
    )
    expected_public = (
        f"{values['FIVEBR_APT_REMOTE_ROOT']}/"
        f"{expected_current}"
    )

    ssh_alias = os.environ.get(
        "FIVEBR_APT_SSH_ALIAS",
        "apt-vps",
    )

    link_command = (
        'printf "CURRENT=%s\\n" '
        '"$(readlink /var/www/apt/current)"; '
        'printf "PREVIOUS=%s\\n" '
        '"$(readlink /var/www/apt/previous)"; '
        'printf "PUBLIC=%s\\n" '
        '"$(readlink -f /var/www/apt/public)"'
    )

    link_result = run_command(
        [
            "ssh",
            ssh_alias,
            link_command,
        ]
    )

    links: dict[str, str] = {}

    for line in link_result.stdout.splitlines():
        if "=" not in line:
            continue

        key, value = line.split("=", 1)
        links[key] = value

    current = links.get("CURRENT", "")
    previous = links.get("PREVIOUS", "")
    public = links.get("PUBLIC", "")

    if current != expected_current:
        raise ReleaseError(
            "remote current link mismatch: "
            f"expected {expected_current}, "
            f"got {current or '<empty>'}"
        )

    if public != expected_public:
        raise ReleaseError(
            "remote public link mismatch: "
            f"expected {expected_public}, "
            f"got {public or '<empty>'}"
        )

    apt_base_url = os.environ.get(
        "FIVEBR_APT_PUBLIC_URL",
        "https://apt.5ibr.com",
    ).rstrip("/")

    if network_via == "apt-vps":
        remote_result = (
            execute_remote_network_verify(
                version=version,
                ssh_alias=ssh_alias,
                apt_base_url=apt_base_url,
            )
        )

        return {
            "verified": True,
            "version": version,
            "tag": validated_tag,
            "release": release_name,
            "current": current,
            "previous": previous,
            "public": public,
            "candidate": remote_result[
                "candidate"
            ],
            "release_date_accepted": (
                remote_result[
                    "release_date_accepted"
                ]
            ),
            "apt_host": config["apt_host"],
            "apt_url": apt_base_url,
            "network_via": network_via,
        }

    public_paths = (
        "/5ibr-archive-keyring.gpg",
        "/dists/stable/InRelease",
        "/dists/stable/Release",
        "/dists/stable/Release.gpg",
        (
            "/dists/stable/main/"
            "binary-all/Packages"
        ),
        (
            "/dists/stable/main/"
            "binary-all/Packages.gz"
        ),
        (
            "/pool/main/5/5ibr-infra/"
            f"5ibr-infra_{version}_all.deb"
        ),
    )

    for relative in public_paths:
        run_command(
            [
                "curl",
                "-4",
                "--connect-timeout",
                "10",
                "--max-time",
                "30",
                "-fsSI",
                f"{apt_base_url}{relative}",
            ]
        )

    with tempfile.TemporaryDirectory(
        prefix="5ibr-release-verify-"
    ) as temporary:
        temporary_root = Path(temporary)
        state = temporary_root / "state"
        cache = temporary_root / "cache"
        sources = temporary_root / "5ibr.list"
        keyring = (
            temporary_root
            / "5ibr-archive-keyring.gpg"
        )

        (
            state / "lists" / "partial"
        ).mkdir(
            parents=True,
            exist_ok=True,
        )
        (
            cache / "archives" / "partial"
        ).mkdir(
            parents=True,
            exist_ok=True,
        )

        run_command(
            [
                "curl",
                "-4",
                "-fsSL",
                (
                    f"{apt_base_url}/"
                    "5ibr-archive-keyring.gpg"
                ),
                "-o",
                str(keyring),
            ]
        )

        if (
            not keyring.is_file()
            or keyring.stat().st_size == 0
        ):
            raise ReleaseError(
                "downloaded APT keyring is missing "
                "or empty"
            )

        sources.write_text(
            (
                "deb [signed-by="
                f"{keyring}] "
                f"{apt_base_url} stable main\n"
            ),
            encoding="utf-8",
        )

        apt_common = [
            "-o",
            f"Dir::State={state}",
            "-o",
            f"Dir::Cache={cache}",
            "-o",
            (
                "Dir::Etc::sourcelist="
                f"{sources}"
            ),
            "-o",
            "Dir::Etc::sourceparts=-",
            "-o",
            "APT::Get::List-Cleanup=0",
        ]

        apt_update = run_command(
            [
                "apt-get",
                *apt_common,
                "update",
            ]
        )

        apt_update_text = (
            apt_update.stdout
            + apt_update.stderr
        )

        if (
            "Invalid 'Date' entry"
            in apt_update_text
        ):
            raise ReleaseError(
                "invalid Release Date warning "
                "returned by APT"
            )

        policy_result = run_command(
            [
                "apt-cache",
                *apt_common,
                "policy",
                "5ibr-infra",
            ]
        )

        candidate = ""

        for line in (
            policy_result.stdout.splitlines()
        ):
            stripped = line.strip()

            if stripped.startswith("Candidate:"):
                candidate = stripped.split(
                    ":",
                    1,
                )[1].strip()
                break

        if candidate != version:
            raise ReleaseError(
                "APT candidate mismatch: "
                f"expected {version}, "
                f"got {candidate or '<empty>'}"
            )

    return {
        "verified": True,
        "version": version,
        "tag": validated_tag,
        "release": release_name,
        "current": current,
        "previous": previous,
        "public": public,
        "candidate": candidate,
        "release_date_accepted": True,
        "apt_host": config["apt_host"],
        "apt_url": apt_base_url,
        "network_via": network_via,
    }


def validate_verify_execution(
    tag: str | None,
) -> dict[str, Any]:
    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    validated_tag = validate_release_tag(tag)
    version = read_version()
    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    return {
        "execute": True,
        "ready": True,
        "version": version,
        "tag": validated_tag,
        "release": release_name,
        "expected_current": (
            f"releases/{release_name}"
        ),
        "apt_host": config["apt_host"],
        "checks": [
            "verify-current-link",
            "verify-previous-link",
            "verify-https-files",
            "verify-release-date",
            "verify-apt-signature",
            "verify-apt-candidate",
        ],
        "verified": False,
    }


def read_rollback_links() -> dict[str, str]:
    ssh_alias = os.environ.get(
        "FIVEBR_APT_SSH_ALIAS",
        "apt-vps",
    )

    result = run_command(
        [
            "ssh",
            ssh_alias,
            (
                'printf "CURRENT=%s\\n" '
                '"$(readlink /var/www/apt/current)"; '
                'printf "PREVIOUS=%s\\n" '
                '"$(readlink /var/www/apt/previous)"'
            ),
        ]
    )

    links: dict[str, str] = {}

    for line in result.stdout.splitlines():
        if "=" not in line:
            continue

        key, value = line.split("=", 1)

        if key in {
            "CURRENT",
            "PREVIOUS",
        }:
            links[key] = value

    return {
        "current": links.get("CURRENT", ""),
        "previous": links.get("PREVIOUS", ""),
    }


def rollback_target_from_previous(
    previous: str,
) -> str:
    prefix = "releases/"

    if not previous:
        raise ReleaseError(
            "previous release is not available"
        )

    if not previous.startswith(prefix):
        raise ReleaseError(
            "previous release link is invalid"
        )

    target_release = previous[len(prefix):]

    try:
        validated = validate_release_tag_syntax(
            target_release
        )
    except ReleaseError as error:
        raise ReleaseError(
            "previous release link is invalid"
        ) from error

    if previous != f"{prefix}{validated}":
        raise ReleaseError(
            "previous release link is invalid"
        )

    return validated


def validate_rollback_approval(
    *,
    target_release: str,
    approval: str | None,
    dry_run: bool,
) -> None:
    if dry_run and approval is not None:
        raise ReleaseError(
            "rollback approval is not allowed "
            "in dry-run mode"
        )

    if (
        approval is not None
        and approval != target_release
    ):
        raise ReleaseError(
            "rollback approval does not match "
            "previous release: "
            f"expected {target_release}, "
            f"got {approval}"
        )


def rollback_dry_run_payload(
    approval: str | None,
) -> dict[str, Any]:
    links = read_rollback_links()

    current = links["current"]
    previous = links["previous"]

    target_release = (
        rollback_target_from_previous(
            previous
        )
    )

    validate_rollback_approval(
        target_release=target_release,
        approval=approval,
        dry_run=True,
    )

    return {
        "dry_run": True,
        "current": current,
        "target": previous,
        "target_release": target_release,
        "approval_required": True,
        "required_approval": target_release,
        "approval_option": (
            "--approve-rollback "
            f"{target_release}"
        ),
        "steps": [
            "read-current-and-previous",
            "validate-rollback-target",
            "approval-gate",
            "run-restricted-rollback-command",
            "verify",
        ],
        "rolled_back": False,
        "verified": False,
    }


def validate_rollback_execution(
    approval: str | None,
) -> dict[str, Any]:
    links = read_rollback_links()

    current = links["current"]
    previous = links["previous"]

    target_release = (
        rollback_target_from_previous(
            previous
        )
    )

    validate_rollback_approval(
        target_release=target_release,
        approval=approval,
        dry_run=False,
    )

    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    approved = approval == target_release

    return {
        "execute": True,
        "ready": True,
        "current": current,
        "target": previous,
        "target_release": target_release,
        "approval_required": True,
        "approval_received": approved,
        "required_approval": target_release,
        "approval_option": (
            "--approve-rollback "
            f"{target_release}"
        ),
        "release_env": config["release_env"],
        "steps": [
            "read-current-and-previous",
            "validate-rollback-target",
            "approval-gate",
            "run-restricted-rollback-command",
            "verify",
        ],
        "rolled_back": False,
        "verified": False,
    }


def execute_rollback(
    approval: str | None,
) -> dict[str, Any]:
    links = read_rollback_links()

    current_before = links["current"]
    previous_before = links["previous"]

    target_release = (
        rollback_target_from_previous(
            previous_before
        )
    )

    validate_rollback_approval(
        target_release=target_release,
        approval=approval,
        dry_run=False,
    )

    if approval is None:
        raise ReleaseError(
            "rollback approval is required"
        )

    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    ssh_alias = os.environ.get(
        "FIVEBR_APT_SSH_ALIAS",
        "apt-vps",
    )

    rollback_result = run_command(
        [
            "ssh",
            ssh_alias,
            (
                "sudo /usr/local/sbin/"
                f"5ibr-apt-rollback {target_release}"
            ),
        ]
    )

    verify_result = execute_verify(
        target_release,
        "apt-vps",
        allow_historical_release=True,
    )

    if (
        verify_result.get("previous")
        != current_before
    ):
        raise ReleaseError(
            "rollback previous link mismatch: "
            f"expected {current_before}, "
            "got "
            f"{verify_result.get('previous') or '<empty>'}"
        )

    return {
        "execute": True,
        "ready": True,
        "approval_required": True,
        "approval_received": True,
        "required_approval": target_release,
        "approval_option": (
            "--approve-rollback "
            f"{target_release}"
        ),
        "release_env": config["release_env"],
        "target": previous_before,
        "target_release": target_release,
        "current_before": current_before,
        "previous_before": previous_before,
        "current": verify_result.get(
            "current"
        ),
        "previous": verify_result.get(
            "previous"
        ),
        "public": verify_result.get(
            "public"
        ),
        "candidate": verify_result.get(
            "candidate"
        ),
        "release_date_accepted": (
            verify_result.get(
                "release_date_accepted"
            )
        ),
        "network_via": verify_result.get(
            "network_via"
        ),
        "apt_host": verify_result.get(
            "apt_host"
        ),
        "apt_url": verify_result.get(
            "apt_url"
        ),
        "remote_output": (
            rollback_result.stdout.strip()
        ),
        "steps": [
            "read-current-and-previous",
            "validate-rollback-target",
            "approval-gate",
            "run-restricted-rollback-command",
            "verify",
        ],
        "rolled_back": True,
        "verified": bool(
            verify_result.get("verified")
        ),
    }


def publish_release_name(
    tag: str | None,
) -> tuple[str, str]:
    validated_tag = validate_release_tag(tag)
    version = read_version()

    release_name = (
        validated_tag
        if validated_tag is not None
        else f"v{version}"
    )

    return version, release_name


def validate_publish_approval(
    *,
    release_name: str,
    approval: str | None,
    dry_run: bool,
) -> None:
    if dry_run and approval is not None:
        raise ReleaseError(
            "promotion approval is not allowed "
            "in dry-run mode"
        )

    if (
        approval is not None
        and approval != release_name
    ):
        raise ReleaseError(
            "promotion approval does not match "
            f"release: expected {release_name}, "
            f"got {approval}"
        )


def publish_dry_run_payload(
    tag: str | None,
    approval: str | None,
) -> dict[str, Any]:
    version, release_name = (
        publish_release_name(tag)
    )

    validate_publish_approval(
        release_name=release_name,
        approval=approval,
        dry_run=True,
    )

    return {
        "dry_run": True,
        "version": version,
        "tag": release_name,
        "release": release_name,
        "approval_required": True,
        "required_approval": release_name,
        "approval_option": (
            f"--approve-promote {release_name}"
        ),
        "steps": [
            "validate",
            "build",
            "stage",
            "approval-gate",
            "promote",
            "verify",
        ],
        "built": False,
        "staged": False,
        "promoted": False,
        "verified": False,
    }


def execute_publish_until_approval(
    tag: str | None,
    approval: str | None,
) -> dict[str, Any]:
    version, release_name = (
        publish_release_name(tag)
    )

    validate_publish_approval(
        release_name=release_name,
        approval=approval,
        dry_run=False,
    )

    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    if approval is not None:
        promote_result = execute_promote(
            release_name
        )

        verify_result = execute_verify(
            release_name,
            "apt-vps",
        )

        return {
            "execute": True,
            "ready": True,
            "version": version,
            "tag": release_name,
            "release": release_name,
            "release_env": config["release_env"],
            "steps": [
                "validate",
                "build",
                "stage",
                "approval-gate",
                "promote",
                "verify",
            ],
            "built": False,
            "staged": True,
            "awaiting_approval": False,
            "approval_required": True,
            "approval_received": True,
            "required_approval": release_name,
            "approval_option": (
                f"--approve-promote {release_name}"
            ),
            "promoted": bool(
                promote_result.get("promoted")
            ),
            "verified": bool(
                verify_result.get("verified")
            ),
            "current": verify_result.get(
                "current"
            ),
            "previous": verify_result.get(
                "previous"
            ),
            "public": verify_result.get(
                "public"
            ),
            "candidate": verify_result.get(
                "candidate"
            ),
            "release_date_accepted": (
                verify_result.get(
                    "release_date_accepted"
                )
            ),
            "network_via": verify_result.get(
                "network_via"
            ),
            "apt_host": verify_result.get(
                "apt_host"
            ),
            "apt_url": verify_result.get(
                "apt_url"
            ),
            "remote_output": promote_result.get(
                "remote_output"
            ),
        }

    build_result = execute_local_build(
        release_name
    )

    # execute_stage performs its own clean-worktree and
    # repository-completeness checks before any remote write.
    stage_result = execute_stage(
        release_name
    )

    return {
        "execute": True,
        "ready": True,
        "version": version,
        "tag": release_name,
        "release": release_name,
        "release_env": config["release_env"],
        "steps": [
            "validate",
            "build",
            "stage",
            "approval-gate",
            "promote",
            "verify",
        ],
        "built": bool(
            build_result.get("built")
        ),
        "staged": bool(
            stage_result.get("staged")
        ),
        "awaiting_approval": True,
        "approval_required": True,
        "approval_received": False,
        "required_approval": release_name,
        "approval_option": (
            f"--approve-promote {release_name}"
        ),
        "resume_command": (
            "5ibr-release publish --execute "
            f"--tag {release_name} "
            f"--approve-promote {release_name}"
        ),
        "promoted": False,
        "verified": False,
        "package": build_result.get("package"),
        "checksum": build_result.get("checksum"),
        "repository": build_result.get(
            "repository"
        ),
        "remote_target": stage_result.get(
            "remote_target"
        ),
    }


def validate_publish_execution(
    tag: str | None,
    approval: str | None,
) -> dict[str, Any]:
    version, release_name = (
        publish_release_name(tag)
    )

    # Check the explicit approval token before Git state so
    # configuration mistakes produce the precise error.
    validate_publish_approval(
        release_name=release_name,
        approval=approval,
        dry_run=False,
    )

    if not worktree_clean():
        raise ReleaseError(
            "worktree is not clean"
        )

    config = validate_config(
        DEFAULT_RELEASE_ENV
    )

    approved = approval == release_name

    return {
        "execute": True,
        "ready": True,
        "version": version,
        "tag": release_name,
        "release": release_name,
        "approval_required": True,
        "approval_received": approved,
        "required_approval": release_name,
        "approval_option": (
            f"--approve-promote {release_name}"
        ),
        "release_env": config["release_env"],
        "steps": [
            "validate",
            "build",
            "stage",
            "approval-gate",
            "promote",
            "verify",
        ],
        "built": False,
        "staged": False,
        "promoted": False,
        "verified": False,
    }


def print_payload(
    payload: dict[str, Any],
    *,
    as_json: bool,
) -> None:
    if as_json:
        print(
            json.dumps(
                payload,
                indent=2,
                sort_keys=True,
            )
        )
        return

    for key, value in payload.items():
        print(f"{key}: {value}")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="5ibr-release",
        description=(
            "Build and validate 5ibr Infrastructure "
            "release artifacts."
        ),
    )

    subparsers = parser.add_subparsers(
        dest="command",
        required=True,
    )

    status_parser = subparsers.add_parser(
        "status",
        help="Show release source status.",
    )
    status_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    validate_parser = subparsers.add_parser(
        "validate",
        help="Validate the local release configuration.",
    )
    validate_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    build_parser_command = subparsers.add_parser(
        "build",
        help="Build release artifacts.",
    )

    build_mode = (
        build_parser_command.add_mutually_exclusive_group(
            required=True,
        )
    )
    build_mode.add_argument(
        "--dry-run",
        action="store_true",
    )
    build_mode.add_argument(
        "--execute",
        action="store_true",
    )

    build_parser_command.add_argument(
        "--tag",
    )
    build_parser_command.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    stage_parser = subparsers.add_parser(
        "stage",
        help=(
            "Upload a completed local repository "
            "to remote incoming staging."
        ),
    )

    stage_mode = (
        stage_parser.add_mutually_exclusive_group(
            required=True,
        )
    )
    stage_mode.add_argument(
        "--dry-run",
        action="store_true",
    )
    stage_mode.add_argument(
        "--execute",
        action="store_true",
    )

    stage_parser.add_argument(
        "--tag",
    )
    stage_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    promote_parser = subparsers.add_parser(
        "promote",
        help=(
            "Promote a staged APT release using "
            "the restricted remote command."
        ),
    )

    promote_mode = (
        promote_parser.add_mutually_exclusive_group(
            required=True,
        )
    )
    promote_mode.add_argument(
        "--dry-run",
        action="store_true",
    )
    promote_mode.add_argument(
        "--execute",
        action="store_true",
    )

    promote_parser.add_argument(
        "--tag",
    )
    promote_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    verify_parser = subparsers.add_parser(
        "verify",
        help=(
            "Verify the published APT release "
            "without changing production."
        ),
    )

    verify_mode = (
        verify_parser.add_mutually_exclusive_group(
            required=True,
        )
    )
    verify_mode.add_argument(
        "--dry-run",
        action="store_true",
    )
    verify_mode.add_argument(
        "--execute",
        action="store_true",
    )

    verify_parser.add_argument(
        "--tag",
    )
    verify_parser.add_argument(
        "--network-via",
        choices=(
            "local",
            "apt-vps",
        ),
        default="local",
    )
    verify_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    rollback_parser = subparsers.add_parser(
        "rollback",
        help=(
            "Plan or execute a guarded rollback "
            "to the previous release."
        ),
    )

    rollback_mode = (
        rollback_parser.add_mutually_exclusive_group(
            required=True,
        )
    )
    rollback_mode.add_argument(
        "--dry-run",
        action="store_true",
    )
    rollback_mode.add_argument(
        "--execute",
        action="store_true",
    )

    rollback_parser.add_argument(
        "--approve-rollback",
    )
    rollback_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    publish_parser = subparsers.add_parser(
        "publish",
        help=(
            "Run the guarded release publishing "
            "pipeline."
        ),
    )

    publish_mode = (
        publish_parser.add_mutually_exclusive_group(
            required=True,
        )
    )
    publish_mode.add_argument(
        "--dry-run",
        action="store_true",
    )
    publish_mode.add_argument(
        "--execute",
        action="store_true",
    )

    publish_parser.add_argument(
        "--tag",
    )
    publish_parser.add_argument(
        "--approve-promote",
    )
    publish_parser.add_argument(
        "--json",
        action="store_true",
        dest="as_json",
    )

    return parser


def main() -> int:
    parser = build_parser()
    args = parser.parse_args()

    try:
        if args.command == "status":
            print_payload(
                status_payload(),
                as_json=args.as_json,
            )
            return 0

        if args.command == "validate":
            print_payload(
                validate_config(
                    DEFAULT_RELEASE_ENV
                ),
                as_json=args.as_json,
            )
            return 0

        if args.command == "build":
            if args.dry_run:
                payload = build_dry_run_payload(
                    args.tag
                )
            else:
                payload = execute_local_build(
                    args.tag
                )

            print_payload(
                payload,
                as_json=args.as_json,
            )
            return 0

        if args.command == "stage":
            if args.dry_run:
                payload = stage_dry_run_payload(
                    args.tag
                )
            else:
                payload = execute_stage(
                    args.tag
                )

            print_payload(
                payload,
                as_json=args.as_json,
            )
            return 0

        if args.command == "promote":
            if args.dry_run:
                payload = promote_dry_run_payload(
                    args.tag
                )
            else:
                payload = execute_promote(
                    args.tag
                )

            print_payload(
                payload,
                as_json=args.as_json,
            )
            return 0

        if args.command == "verify":
            if args.dry_run:
                payload = verify_dry_run_payload(
                    args.tag,
                    args.network_via,
                )
            else:
                payload = execute_verify(
                    args.tag,
                    args.network_via,
                )

            print_payload(
                payload,
                as_json=args.as_json,
            )
            return 0

        if args.command == "rollback":
            if args.dry_run:
                payload = rollback_dry_run_payload(
                    args.approve_rollback,
                )
            else:
                payload = execute_rollback(
                    args.approve_rollback,
                )

            print_payload(
                payload,
                as_json=args.as_json,
            )
            return 0

        if args.command == "publish":
            if args.dry_run:
                payload = publish_dry_run_payload(
                    args.tag,
                    args.approve_promote,
                )
            else:
                payload = execute_publish_until_approval(
                    args.tag,
                    args.approve_promote,
                )

            print_payload(
                payload,
                as_json=args.as_json,
            )
            return 0

        raise ReleaseError(
            f"unsupported command: {args.command}"
        )

    except ReleaseError as exc:
        print(
            f"5ibr-release error: {exc}",
            file=sys.stderr,
        )
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
