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

from __future__ import annotations

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_sign(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-signchanges": "0.1"},
    ):
        pytest.skip("No `debsigs-signchanges` or `debsigs --list` support")

    with test_cfg.cfg_with_tempd() as cfg:
        pub_key: Final = test_cfg.pub_key
        changes_orig: Final = test_cfg.changes_orig

        changes_signed: Final = changes_orig.copy_to(cfg.path.work)
        assert changes_signed.get_different_files(cfg, changes_orig) == []
        for deb in changes_signed.debs:
            assert util.debsigs_list(cfg, deb) == []

        sign_key: Final = util.get_signing_subkey(pub_key)
        env_with_path: Final = dict(cfg.env)
        env_with_path["PATH"] = f"{cfg.prog.debsigs.parent}:{env_with_path['PATH']}"
        if "DEBSIGSSIG" in env_with_path:
            del env_with_path["DEBSIGSSIG"]
        env_with_path["DEBSIGSOPTIONS"] = f"--default-key={sign_key.key_id}"

        subprocess.check_call(  # noqa: S603
            [cfg.prog.debsigs.parent / "debsigs-signchanges", changes_signed.path],
            cwd=cfg.path.work,
            env=env_with_path,
        )

        changes_signed.verify(cfg)
        assert changes_signed.get_different_files(cfg, changes_orig) == sorted(
            deb.name for deb in changes_signed.debs
        )

        for deb in changes_signed.debs:
            lines_maint_only = util.debsigs_list(cfg, deb)
            match lines_maint_only:
                case [single] if single.sig_type == "maint" and single.key_id == sign_key.key_id:
                    pass

                case _:
                    raise AssertionError(repr((changes_signed, deb, lines_maint_only)))
