# Copyright 2023 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

EAPI=8

DISTUTILS_EXT=1
DISTUTILS_USE_PEP517=setuptools
PYTHON_COMPAT=( python3_{10..13} )
inherit distutils-r1 edo

MY_PN=PyKCS11
MY_P=${MY_PN}-${PV}

DESCRIPTION="PKCS#11 Wrapper for Python"
HOMEPAGE="
	https://pypi.org/project/pykcs11/
	https://github.com/LudovicRousseau/PyKCS11
"

SRC_URI="https://github.com/LudovicRousseau/PyKCS11/archive/refs/tags/${PV}.tar.gz -> ${P}.gh.tar.gz"
S="${WORKDIR}/${MY_P}"
LICENSE="GPL-2+"
SLOT="0"
KEYWORDS="amd64 x86"
IUSE="examples"

RDEPEND="
	dev-lang/swig
	dev-python/asn1crypto[${PYTHON_USEDEP}]
"
BDEPEND="
	test? (
		dev-libs/softhsm
	)
"

DOCS=( README.md )
EPYTEST_PLUGINS=( )

distutils_enable_tests pytest
distutils_enable_sphinx docs

python_install_all() {
	if use examples; then
		dodoc -r samples
	fi

	distutils-r1_python_install_all
}

src_test() {
	local -x PYKCS11LIB="${BROOT}/usr/$(get_libdir)/softhsm/libsofthsm2.so"
	local -x PKCS11_TOKEN_LABEL="A token"
	local -x PKCS11_TOKEN_PIN="1234"
	local -x PKCS11_TOKEN_SO_PIN="123456"

	mkdir -p "${HOME}/.config/softhsm2" || die
	cat > "${HOME}/.config/softhsm2/softhsm2.conf" <<- EOF || die "Failed to create config"
		directories.tokendir = ${T}
		objectstore.backend = file
	EOF

	edo softhsm2-util --init-token --slot 0 \
		--label ${PKCS11_TOKEN_LABEL} \
		--pin ${PKCS11_TOKEN_PIN} \
		--so-pin ${PKCS11_TOKEN_SO_PIN}

	distutils-r1_src_test
}

python_test() {
	rm -rf "${MY_PN}" || die
	epytest test
}