# SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
# SPDX-License-Identifier: GPL-2.0-or-later
"""Unit tests for the `debsigs-autosign` tool."""

from __future__ import annotations

import shutil
import subprocess  # noqa: S404
import typing

import pytest

from . import util
from .util import test_cfg  # noqa: F401  # pytest fixture


if typing.TYPE_CHECKING:
    from typing import Final


def test_autosign(test_cfg: util.ConfigAggr) -> None:  # noqa: F811  # pytest fixture
    """Sign files in different ways."""
    if not test_cfg.has_all_features(
        {"cmd-list": "1", "cmd-sign": "1", "i-gpg": "1", "tool-autosign": "0.1"},
    ):
        pytest.skip("No `debsigs-autosign` or `debsigs --list` support")

    with test_cfg.cfg_with_tempd() as cfg:
        pub_key: Final = test_cfg.pub_key
        pkg_orig: Final = test_cfg.changes_orig.debs[0]

        pkg_signed: Final = cfg.path.work / pkg_orig.name
        shutil.copy2(pkg_orig, pkg_signed)
        assert util.debsigs_list(cfg, pkg_signed) == []

        env_with_path: Final = dict(cfg.env)
        env_with_path["PATH"] = f"{cfg.prog.debsigs.parent}:{env_with_path['PATH']}"

        subprocess.run(  # noqa: S603
            [cfg.prog.debsigs.parent / "debsigs-autosign", "maint"],
            check=True,
            cwd=cfg.path.work,
            encoding="UTF-8",
            env=env_with_path,
            input=f"{pkg_signed}\n",
        )
        lines_maint_only: Final = util.debsigs_list(cfg, pkg_signed)

        sign_key: Final = util.get_signing_subkey(pub_key)
        match lines_maint_only:
            case [single] if single.sig_type == "maint" and single.key_id == sign_key.key_id:
                pass

            case _:
                raise AssertionError(repr(lines_maint_only))

        # OK, let's do that again...
        subprocess.run(  # noqa: S603
            [cfg.prog.debsigs.parent / "debsigs-autosign", "origin"],
            check=True,
            cwd=cfg.path.work,
            encoding="UTF-8",
            env=env_with_path,
            input=f"{pkg_signed}\n",
        )
        lines_both: Final = util.debsigs_list(cfg, pkg_signed)

        match lines_both:
            case [
                maint,
                origin,
            ] if (
                maint.sig_type == "maint"
                and maint.key_id == sign_key.key_id
                and origin.sig_type == "origin"
                and origin.key_id == sign_key.key_id
            ):
                pass

            case _:
                raise AssertionError(repr(lines_both))
