import functools
import os
import subprocess
from typing import Any

from debputy.plugin.api import (
    define_debputy_plugin,
    BinaryCtrlAccessor,
    PackageProcessingContext,
)
from debputy.util import _error

plugin_definition = define_debputy_plugin()


@functools.lru_cache
def _resolve_libssl_abi(cmd: str) -> str:
    try:
        return subprocess.check_output([cmd]).strip().decode("utf-8")
    except FileNotFoundError:
        _error(
            "The perl-openssl plugin requires that perl-openssl-defaults + libssl-dev is installed"
        )
    except subprocess.CalledProcessError as e:
        _error(f"Command {cmd} failed. Exit code was: {e.returncode}")


@plugin_definition.metadata_or_maintscript_detector
def perl_openssl_abi(
    _unused: Any,
    ctrl: BinaryCtrlAccessor,
    _context: PackageProcessingContext,
) -> None:
    cmd = os.environ.get(
        "_PERL_SSL_DEFAULTS_TEST_PATH",
        "/usr/share/perl-openssl-defaults/get-libssl-abi",
    )
    abi = _resolve_libssl_abi(cmd)
    ctrl.substvars.add_dependency("perl:Depends", f"perl-openssl-abi-{abi}")
