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

EAPI=8

PYTHON_COMPAT=( python3_{11..15} )

inherit python-single-r1

DESCRIPTION="Enhanced sampling methods for molecular dynamics"
HOMEPAGE="https://www.plumed.org"
SRC_URI="https://github.com/plumed/plumed2/releases/download/v${PV}/plumed-src-${PV}.tgz"

LICENSE="LGPL-3+"
SLOT="0"
KEYWORDS="~amd64"
IUSE="fftw gsl mpi openmp pycv"

REQUIRED_USE="pycv? ( ${PYTHON_REQUIRED_USE} )"

BDEPEND="
	pycv? (
		$(python_gen_cond_dep '
			dev-python/cython[${PYTHON_USEDEP}]
			dev-python/pybind11[${PYTHON_USEDEP}]
			dev-python/setuptools[${PYTHON_USEDEP}]
		')
	)
"
# PLUMED needs BLAS/LAPACK and falls back to internal copies when they
# are not detected; require the system ones instead.
DEPEND="
	virtual/blas
	virtual/lapack
	virtual/zlib
	fftw? ( sci-libs/fftw:3.0= )
	gsl? ( sci-libs/gsl:= )
	mpi? ( virtual/mpi )
	pycv? (
		${PYTHON_DEPS}
		$(python_gen_cond_dep 'dev-python/numpy[${PYTHON_USEDEP}]')
	)
"
RDEPEND="${DEPEND}"

# The regression test suite ships in a separate ~80MB plumed-test
# tarball and upstream notes that some tests fail depending on the
# numerical accuracy of the machine, so it is not packaged here.

src_configure() {
	local myeconfargs=(
		# Keep the configure-time cython interface probe off: when pycv
		# is enabled the wrapper is force-built by make install anyway
		# (see src_install), otherwise we do not want it at all.
		--disable-python
		$(use_enable fftw)
		$(use_enable gsl)
		$(use_enable mpi)
		$(use_enable openmp)
		$(use_enable pycv)
	)

	# The configure script ignores MPICXX on purpose and probes the MPI
	# C++ compiler through CXX/CC instead.
	use mpi && export CC=mpicc CXX=mpicxx

	if use pycv; then
		# pycv embeds a Python interpreter into the kernel library, so
		# pin the interpreter to PYTHON_SINGLE_TARGET
		python_setup
		econf PYTHON_BIN="${EPREFIX}/usr/bin/${EPYTHON}" "${myeconfargs[@]}"
	else
		econf "${myeconfargs[@]}"
	fi
}

src_install() {
	default

	find "${ED}" -name '*.la' -delete || die

	if use pycv; then
		# With pycv enabled make install also rebuilds and installs the
		# cython wrapper into lib/plumed/python for PYTHONPATH use; move
		# it into site-packages so that 'import plumed' works as usual
		local wrapperdir="${ED}/usr/$(get_libdir)/plumed/python"
		[[ -d ${wrapperdir} ]] || die "pycv wrapper missing from install image"
		python_setup
		python_domodule "${wrapperdir}"/*.so
		rm -rf "${wrapperdir}" || die
	fi
}