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

EAPI=8

POSTGRES_COMPAT=( {11..18} )

PYTHON_COMPAT=( python3_{12..14} )
PYTHON_SUBDIRS=( contrib/{pyln-proto,pyln-spec/bolt{1,2,4,7},pyln-client} )
DISTUTILS_OPTIONAL=1
DISTUTILS_USE_PEP517=hatchling

RUST_MIN_VER="1.87.0"
CARGO_OPTIONAL=1
CRATES="
	aho-corasick-1.1.5
	android_system_properties-0.1.6
	anstream-1.0.0
	anstyle-1.0.14
	anstyle-parse-1.0.0
	anstyle-query-1.1.5
	anstyle-wincon-3.0.11
	anyhow-1.0.104
	arbitrary-1.5.0
	arc-swap-1.9.3
	arrayvec-0.7.8
	asn1-rs-0.7.2
	asn1-rs-derive-0.6.0
	asn1-rs-impl-0.2.0
	async-trait-0.1.92
	atomic-waker-1.1.2
	autocfg-1.5.1
	axum-0.8.9
	axum-core-0.5.6
	axum-server-0.8.0
	base58ck-0.1.101
	base64-0.22.1
	bech32-0.11.1
	bit-set-0.8.0
	bit-vec-0.8.0
	bitcoin-0.32.102
	bitcoin-consensus-encoding-1.3.0
	bitcoin-internals-0.7.0
	bitcoin-io-0.1.101
	bitcoin-payment-instructions-0.8.0
	bitcoin-units-0.1.101
	bitcoin_hashes-0.14.101
	bitflags-1.3.2
	bitflags-2.13.2
	bitreq-0.4.3
	block-buffer-0.10.4
	block-buffer-0.12.1
	bumpalo-3.20.3
	bytes-1.12.1
	cc-1.10.0
	cfg-if-1.0.5
	chacha20-0.10.2
	chrono-0.4.45
	colorchoice-1.0.5
	const-oid-0.10.2
	core-foundation-sys-0.8.7
	cpufeatures-0.2.17
	cpufeatures-0.3.1
	crc32fast-1.5.3
	crypto-common-0.1.7
	crypto-common-0.2.2
	data-encoding-2.11.1
	defmt-1.2.0
	defmt-macros-1.2.0
	defmt-parser-1.1.0
	der-parser-10.0.0
	deranged-0.5.9
	derive_arbitrary-1.5.0
	digest-0.10.7
	digest-0.11.3
	displaydoc-0.2.7
	dnssec-prover-0.6.10
	either-1.19.0
	engineioxide-0.16.2
	engineioxide-core-0.1.0
	env_filter-2.0.0
	env_logger-0.11.11
	equivalent-1.0.3
	errno-0.3.14
	fastrand-2.5.0
	find-msvc-tools-0.1.15
	fixedbitset-0.5.7
	flate2-1.1.10
	fnv-1.0.7
	foldhash-0.1.5
	form_urlencoded-1.2.2
	fs-err-3.3.2
	futures-0.3.34
	futures-channel-0.3.34
	futures-core-0.3.34
	futures-executor-0.3.34
	futures-io-0.3.34
	futures-macro-0.3.34
	futures-sink-0.3.34
	futures-task-0.3.34
	futures-util-0.3.34
	generator-0.7.5
	generic-array-0.14.7
	getrandom-0.2.17
	getrandom-0.3.4
	getrandom-0.4.3
	h2-0.4.20
	hashbrown-0.13.2
	hashbrown-0.15.5
	hashbrown-0.17.1
	heck-0.5.0
	hex-0.4.3
	hex-conservative-0.2.3
	hex-conservative-1.3.0
	hex_lit-0.1.1
	http-1.5.0
	http-body-1.1.0
	http-body-util-0.1.5
	httparse-1.10.1
	httpdate-1.0.3
	hybrid-array-0.4.15
	hyper-1.12.0
	hyper-timeout-0.5.2
	hyper-util-0.1.21
	iana-time-zone-0.1.65
	iana-time-zone-haiku-0.1.2
	icu_collections-2.1.1
	icu_locale_core-2.1.1
	icu_normalizer-2.1.1
	icu_normalizer_data-2.1.1
	icu_properties-2.1.2
	icu_properties_data-2.1.2
	icu_provider-2.1.1
	idna-1.1.0
	idna_adapter-1.2.1
	indexmap-2.14.2
	is_terminal_polyfill-1.70.2
	itertools-0.14.0
	itoa-1.0.18
	jiff-0.2.38
	jiff-core-0.1.1
	jiff-static-0.2.38
	js-sys-0.3.106
	lazy_static-1.5.1
	libc-0.2.191
	libm-0.2.16
	lightning-0.2.7
	lightning-invoice-0.34.1
	lightning-macros-0.2.1
	lightning-types-0.3.5
	linux-raw-sys-0.12.1
	litemap-0.8.3
	lock_api-0.4.14
	log-0.4.34
	log-panics-2.1.0
	loom-0.5.6
	matchers-0.2.0
	matchit-0.8.4
	matchit-0.9.2
	memchr-2.8.3
	mime-0.3.17
	mime_guess-2.0.5
	minimal-lexical-0.2.1
	mio-1.2.4
	multimap-0.10.1
	nom-7.1.3
	nu-ansi-term-0.50.3
	num-bigint-0.4.8
	num-conv-0.1.0
	num-integer-0.1.47
	num-traits-0.2.19
	oid-registry-0.8.1
	once_cell-1.21.4
	once_cell_polyfill-1.70.2
	parking_lot-0.12.5
	parking_lot_core-0.9.12
	pem-3.0.6
	percent-encoding-2.3.2
	petgraph-0.8.3
	pin-project-1.1.13
	pin-project-internal-1.1.13
	pin-project-lite-0.2.17
	portable-atomic-1.15.0
	portable-atomic-util-0.2.8
	possiblyrandom-0.2.1
	potential_utf-0.1.6
	powerfmt-0.2.1
	ppv-lite86-0.2.21
	prettyplease-0.2.37
	proc-macro2-1.0.107
	proptest-1.11.0
	prost-0.14.4
	prost-build-0.14.4
	prost-derive-0.14.4
	prost-types-0.14.4
	protoc-bin-vendored-3.3.0
	protoc-bin-vendored-linux-aarch_64-3.3.0
	protoc-bin-vendored-linux-ppcle_64-3.3.0
	protoc-bin-vendored-linux-s390_64-3.3.0
	protoc-bin-vendored-linux-x86_32-3.3.0
	protoc-bin-vendored-linux-x86_64-3.3.0
	protoc-bin-vendored-macos-aarch_64-3.3.0
	protoc-bin-vendored-macos-x86_64-3.3.0
	protoc-bin-vendored-win32-3.3.0
	pulldown-cmark-0.13.5
	pulldown-cmark-to-cmark-22.0.3
	quick-error-1.2.3
	quick-xml-0.41.0
	quote-1.0.47
	r-efi-5.3.0
	r-efi-6.0.0
	rand-0.9.5
	rand-0.10.3
	rand_chacha-0.9.0
	rand_core-0.9.5
	rand_core-0.10.1
	rand_xorshift-0.4.0
	rcgen-0.14.7
	redox_syscall-0.5.18
	regex-1.13.1
	regex-automata-0.4.18
	regex-syntax-0.8.11
	ring-0.17.14
	roxmltree-0.20.0
	roxmltree_to_serde-0.6.2
	rust-embed-8.13.0
	rust-embed-impl-8.13.0
	rust-embed-utils-8.13.0
	rusticata-macros-4.1.0
	rustix-1.1.6
	rustls-0.23.46
	rustls-pki-types-1.15.1
	rustls-webpki-0.103.16
	rustversion-1.0.23
	rusty-fork-0.3.1
	ryu-1.0.23
	same-file-1.0.6
	scoped-tls-1.0.1
	scopeguard-1.2.0
	secp256k1-0.29.1
	secp256k1-sys-0.10.1
	serde-1.0.229
	serde_core-1.0.229
	serde_derive-1.0.229
	serde_json-1.0.154
	serde_path_to_error-0.1.20
	serde_qs-1.1.3
	serde_urlencoded-0.7.1
	serde_yaml_ng-0.10.0
	sha1-0.10.7
	sha1-0.11.0
	sha2-0.11.0
	sharded-slab-0.1.7
	shlex-2.0.1
	signal-hook-registry-1.4.8
	simd-adler32-0.3.10
	slab-0.4.12
	smallvec-1.16.4
	socket2-0.6.5
	socketioxide-0.16.3
	socketioxide-core-0.16.1
	socketioxide-parser-common-0.16.1
	stable_deref_trait-1.2.1
	state-0.6.0
	subtle-2.6.1
	syn-2.0.119
	syn-3.0.9
	sync_wrapper-1.0.2
	synstructure-0.13.2
	synstructure-0.14.0
	tempfile-3.27.0
	thiserror-2.0.21
	thiserror-impl-2.0.21
	thread_local-1.1.10
	time-0.3.45
	time-core-0.1.7
	time-macros-0.2.25
	tinystr-0.8.5
	tokio-1.54.1
	tokio-macros-2.7.2
	tokio-rustls-0.26.6
	tokio-stream-0.1.19
	tokio-test-0.4.6
	tokio-tungstenite-0.26.2
	tokio-tungstenite-0.30.0
	tokio-util-0.7.20
	tonic-0.14.5
	tonic-build-0.14.5
	tonic-prost-0.14.5
	tonic-prost-build-0.14.5
	tower-0.5.3
	tower-http-0.7.1
	tower-layer-0.3.3
	tower-service-0.3.3
	tracing-0.1.44
	tracing-attributes-0.1.31
	tracing-core-0.1.36
	tracing-log-0.2.0
	tracing-subscriber-0.3.23
	try-lock-0.2.5
	tungstenite-0.26.2
	tungstenite-0.30.0
	typenum-1.20.1
	unarray-0.1.4
	unicase-2.10.0
	unicode-ident-1.0.27
	unsafe-libyaml-0.2.11
	untrusted-0.9.0
	url-2.5.8
	utf-8-0.7.6
	utf8_iter-1.0.4
	utf8parse-0.2.2
	utoipa-5.5.0
	utoipa-gen-5.5.0
	utoipa-swagger-ui-9.0.2
	utoipa-swagger-ui-vendored-0.1.2
	valuable-0.1.1
	version_check-0.9.5
	wait-timeout-0.2.1
	walkdir-2.5.0
	want-0.3.2
	wasi-0.11.1+wasi-snapshot-preview1
	wasip2-1.0.1+wasi-0.2.4
	wasm-bindgen-0.2.129
	wasm-bindgen-macro-0.2.129
	wasm-bindgen-macro-support-0.2.129
	wasm-bindgen-shared-0.2.129
	webpki-roots-1.0.11
	winapi-util-0.1.11
	windows-0.48.0
	windows-core-0.62.2
	windows-implement-0.60.2
	windows-interface-0.59.3
	windows-link-0.2.1
	windows-result-0.4.1
	windows-strings-0.5.1
	windows-sys-0.52.0
	windows-sys-0.61.2
	windows-targets-0.48.5
	windows-targets-0.52.6
	windows_aarch64_gnullvm-0.48.5
	windows_aarch64_gnullvm-0.52.6
	windows_aarch64_msvc-0.48.5
	windows_aarch64_msvc-0.52.6
	windows_i686_gnu-0.48.5
	windows_i686_gnu-0.52.6
	windows_i686_gnullvm-0.52.6
	windows_i686_msvc-0.48.5
	windows_i686_msvc-0.52.6
	windows_x86_64_gnu-0.48.5
	windows_x86_64_gnu-0.52.6
	windows_x86_64_gnullvm-0.48.5
	windows_x86_64_gnullvm-0.52.6
	windows_x86_64_msvc-0.48.5
	windows_x86_64_msvc-0.52.6
	wit-bindgen-0.46.0
	writeable-0.6.4
	x509-parser-0.18.1
	yasna-0.5.2
	yoke-0.8.4
	yoke-derive-0.8.4
	zerocopy-0.8.63
	zerocopy-derive-0.8.63
	zerofrom-0.1.8
	zerofrom-derive-0.1.8
	zeroize-1.9.1
	zerotrie-0.2.5
	zerovec-0.11.9
	zerovec-derive-0.11.7
	zip-3.0.0
	zlib-rs-0.6.8
	zmij-1.0.23
	zopfli-0.8.3
"

inherit backports bash-completion-r1 cargo depends distutils-r1 eapi9-ver edo flag-o-matic postgres toolchain-funcs

MyPN=lightning
MyPV=${PV/_}
MyPVR=${MyPV}-gentoo-${PR}

BACKPORTS=(
	# https://github.com/ElementsProject/lightning/pull/8933/commits
	2df7f0e80912d2e834f51ad0b095d38ddc55f5b5	# configure: don't use 'echo -n' under /bin/sh
	6790ec0ec8b074d9df045d9fb6896a9e270e23d0	# configure: be consistent in writing status output to stderr
	68527eef533b6311ea3245d78f4a00c1725ff15c	# configure: fix quoting mistake in setting DEFAULT_CWARNFLAGS in usage()
	96f75cedf6cda1c279d35aae6a16f37fd1dccf3a	# Makefile: don't show config.vars on the LD line in show-flags
	d353bd5de41e4139063a4b5f9c877ff7077874d9	# build: allow overriding CFLAGS, CPPFLAGS, and LDFLAGS
	60249d30bbaa6d9941ba2d25042ee2d12692c995	# Makefile: use standard variables for compiling and linking C programs
	994721897e81aa8c4b15ca7eaca57cb81f1af23e	# build: move -std=gnu11 to CPPFLAGS
	26e1a618e4d04c183891dbe8df36d2e96edab6f3	# configure: fix have_function_sections test
	069ecc66483deb83f0047b66b7e58a510c7cd834	# fix two libwally-core #includes
	b4e1e63f2e7f760fa06a6a1f467d24677a02d5e6	# build: manage installation targets with Make individually
	98851d4eaf7b738ac79551ec1fa1c729f62b5c03	# configure: allow overriding library flags via environment vars
	2e2aaee4cc29085548205bbbb7565110c9f46ca4	# configure: keep -std=gnu11 when CPPFLAGS is set
)

DESCRIPTION="An implementation of Bitcoin's Lightning Network in C"
HOMEPAGE="https://github.com/ElementsProject/${MyPN}"
BACKPORTS_BASE_URI="${HOMEPAGE}/commit/"
SRC_URI="${HOMEPAGE}/archive/refs/tags/v${MyPV}.tar.gz -> ${P}.tar.gz
	https://github.com/zserge/jsmn/archive/v1.0.0.tar.gz -> jsmn-1.0.0.tar.gz
	https://github.com/valyala/gheap/archive/67fc83bc953324f4759e52951921d730d7e65099.tar.gz -> gheap-67fc83b.tar.gz
	rust? ( ${CARGO_CRATE_URIS} )
	$(backports_patch_uris)
"
S="${WORKDIR}/${MyPN}-${MyPV}"

LICENSE="MIT BSD-2 CC0-1.0 GPL-2 LGPL-2.1 LGPL-3"
SLOT="0"
if [[ "${PV}" != *_rc* ]] ; then
	KEYWORDS="~amd64 ~arm ~arm64 ~mips ~ppc ~x86"
fi
IUSE="debug doc +man postgres python rust sqlite test test-full"
RESTRICT="mirror !test? ( test )"

CDEPEND="
	>=dev-libs/libsecp256k1-zkp-0.1.0_pre20220318:=[ecdh,extrakeys(-),recovery,schnorrsig(-)]
	>=dev-libs/libsodium-1.0.16:=
	>=net-libs/libwally-core-1.6.1:0/10[elements]
	|| ( >=sys-libs/libbacktrace-1.0_p20220218:= =sys-libs/libbacktrace-0.0.0_pre20220218:= )
	>=sys-libs/zlib-1.2.13:=
	postgres? ( ${POSTGRES_DEP} )
	python? ( ${PYTHON_DEPS} )
	sqlite? ( >=dev-db/sqlite-3.29.0:= )
"
PYTHON_DEPEND='
	>=dev-python/base58-2.1.1[${PYTHON_USEDEP}]
	<dev-python/bitstring-5_alpha[${PYTHON_USEDEP}]
	!!<dev-python/bitstring-4.3.0
	>=dev-python/coincurve-21.0.0[${PYTHON_USEDEP}]
	>=dev-python/cryptography-46[${PYTHON_USEDEP}]
	>=dev-python/pysocks-1[${PYTHON_USEDEP}]
'
MAKO_DEPEND='
	>=dev-python/mako-1.1.6[${PYTHON_USEDEP}]
'
SPHINX_DEPEND='
	dev-python/recommonmark[${PYTHON_USEDEP}]
	dev-python/sphinx[${PYTHON_USEDEP}]
	dev-python/sphinx-rtd-theme[${PYTHON_USEDEP}]
'
TEST_FULL_DEPEND="${PYTHON_DEPEND}"'
	>=dev-python/cheroot-8[${PYTHON_USEDEP}]
	>=dev-python/ephemeral-port-reserve-1.1.4[${PYTHON_USEDEP}]
	>=dev-python/flask-3.0.0[${PYTHON_USEDEP}]
	>=dev-python/grpcio-1.75.1[${PYTHON_USEDEP}]
	>=dev-python/jsonschema-4.4.0[${PYTHON_USEDEP}]
	>=dev-python/mnemonic-0.21[${PYTHON_USEDEP}]
	>=dev-python/protobuf-6.32.1[${PYTHON_USEDEP}]
	>=dev-python/psycopg-2.9.0:2[${PYTHON_USEDEP}]
	>=dev-python/pytest-8.0.0[${PYTHON_USEDEP}]
	>=dev-python/pytest-xdist-3.6.0[${PYTHON_USEDEP}]
	dev-python/python-bitcointx[${PYTHON_USEDEP}]
	>=dev-python/python-socketio-5.15.0[${PYTHON_USEDEP}]
	>=dev-python/requests-2.32.0[${PYTHON_USEDEP}]
	>=dev-python/websocket-client-1.2.3[${PYTHON_USEDEP}]
'
RDEPEND="${CDEPEND}
	acct-group/lightning
	acct-user/lightning
	python? ( ${PYTHON_DEPEND//'${PYTHON_USEDEP}'/${PYTHON_USEDEP}} )
"
DEPEND="${CDEPEND}
"
BDEPEND="
	acct-group/lightning
	acct-user/lightning
	>=app-misc/jq-1.6
	man? ( app-text/lowdown )
	$(python_gen_any_dep "${MAKO_DEPEND}")
	doc? (
		python? ( $(python_gen_any_dep "${SPHINX_DEPEND}") )
	)
	python? (
		${DISTUTILS_DEPS}
		test? (
			>=dev-python/pytest-7[${PYTHON_USEDEP}]
			${PYTHON_DEPEND//'${PYTHON_USEDEP}'/${PYTHON_USEDEP}}
		)
	)
	rust? (
		${RUST_DEPEND}
		>=dev-libs/protobuf-4[protoc(+)]
	)
	sys-devel/gettext
	virtual/pkgconfig
	test-full? (
		>=net-p2p/bitcoin-core-28.0[cli,daemon,sqlite(+),wallet(+)]
		$(PYTHON_REQ_USE='sqlite' python_gen_any_dep "${TEST_FULL_DEPEND}")
	)
"
REQUIRED_USE="
	|| ( postgres sqlite )
	postgres? ( ${POSTGRES_REQ_USE/||/^^} )
	python? ( ${PYTHON_REQUIRED_USE} )
	test-full? ( test )
"
# FIXME: bundled deps: ccan

PATCHES=(
	"${FILESDIR}/26.09-python-bitcointx.patch"
)

DOCS=( CHANGELOG.md README.md SECURITY.md )

EPYTEST_PLUGINS=( )
EPYTEST_DESELECT=(
	# test depends on machine being "reasonably fast," which we can't guarantee
	test_connection.py::test_no_delay

	# these tests require Internet access, which we don't provide
	test_cln_rs.py::test_bip353
	test_connection.py::test_networkevents
	test_currencyrate.py::test_{apis_batch{1,2},custom_source}
	test_gossip.py::test_announce_{dns_suppressed,and_connect_via_dns}
)
EPYTEST_IGNORE=(
	# we don't depend on any of the installers that Reckless wants
	tests/test_reckless.py
)

efmt() {
	: ${1:?} ; local l ; while read -r l ; do "${!#}" "${l}" ; done < <(fmt "${@:1:$#-1}")
}

re_match() {
	local -n var="${1:?}" ; local regex="${2:?}" ; shift 2
	var=( )
	local each ; for each ; do
		[[ "${each}" =~ ${regex} ]] && var+=( "${each}" )
	done
	(( "${#var[@]}" ))
}

python_check_deps() {
	{ [[ " ${python_need} " != *' mako '* ]] || has_depends -p \
		${MAKO_DEPEND//'${PYTHON_USEDEP}'/"${PYTHON_USEDEP}"} ; } &&
	{ [[ " ${python_need} " != *' sphinx '* ]] || has_depends -p \
		${SPHINX_DEPEND//'${PYTHON_USEDEP}'/"${PYTHON_USEDEP}"} ; } &&
	{ [[ " ${python_need} " != *' test-full '* ]] || has_depends -p \
		${TEST_FULL_DEPEND//'${PYTHON_USEDEP}'/"${PYTHON_USEDEP}"} ; }
}

python_foreach_subdir() {
	local subdir
	for subdir in "${PYTHON_SUBDIRS[@]}" ; do
		pushd -- "${subdir}" >/dev/null || die
		"${@}"
		popd >/dev/null || die
	done
}

pkg_pretend() {
	if [[ ! "${REPLACE_RUNNING_CLIGHTNING}" ]] &&
		[[ -x "${EROOT%/}/usr/bin/lightningd" ]] &&
		{ has_version "<${CATEGORY}/${PN}-$(ver_cut 1-3)" ||
			has_version ">=${CATEGORY}/${PN}-$(ver_cut 1-2).$(($(ver_cut 3)+1))" ; } &&
		[[ "$(find /proc/[0-9]*/exe -xtype f -lname "${EROOT%/}/usr/bin/lightningd*" -print -quit 2>/dev/null)" ||
			-x "${EROOT%/}/run/openrc/started/lightningd" ]]
	then
		efmt eerror <<-EOF
			A potentially incompatible version of the lightningd daemon is currently
			running. Installing version ${PV} would likely cause the running daemon
			to fail when it next spawns a subdaemon process. Please stop the running
			daemon and reattempt this installation, or set REPLACE_RUNNING_CLIGHTNING=1
			if you are certain you know what you are doing.
		EOF
		die 'lightningd is running'
	fi
}

pkg_setup() {
	use postgres && postgres_pkg_setup
	use test && tc-ld-disable-gold	# mock magic doesn't support gold
	use rust && rust_pkg_setup
}

src_unpack() {
	local -a git_crates
	re_match git_crates '\.gh\.tar\.gz$' ${A}
	unpack "${P}.tar.gz" "${git_crates[@]}"
	cd "${S}/external" || die
	rm -r */ || die
	unpack jsmn-1.0.0.tar.gz gheap-67fc83b.tar.gz
	mv jsmn{-1.0.0,} || die
	mv gheap{-*,} || die

	if use rust ; then
		set ${CRATES}
		local A="${*/%/.crate}"
		cargo_src_unpack
	fi
}

src_prepare() {
	backports_apply_patches
	default

	# hack to suppress tools/refresh-submodules.sh
	# and spurious rebuilds due to missing lowdown sources
	sed -e '/^submodcheck:/,/^$/{/^\t/d}' \
		-e '/\bexternal\/lowdown\b/d' \
		-i external/Makefile || die

	# app-text/lowdown actually isn't required unconditionally
	use man || sed -e "/check_command 'lowdown'/,/^fi$/d" -i configure || die

	if ! use sqlite ; then
		# https://github.com/ElementsProject/lightning/issues/8473
		rm plugins/bkpr/test/run-recorder.c || die
	fi

	# don't unconditionally regenerate Python sources
	# and don't try to run git
	sed -e '/^default:/s/\bgen\b\|\$(PYTHON_GENERATED)//g' \
		-e '/^check-source-bolt\s*:/d' \
		-i Makefile || die

	# don't assume uv is installed (or relevant!)
	sed -e 's/\buv run\b//g' -i configure || die

	# don't look for headers or libraries beneath /usr/local
	sed -e '/"Darwin-arm64"/,/^$/d' \
		-e 's/ *\(-[IL]\$(\?\(CPATH\|LIBRARY_PATH\))\? *\)\+/ /g' \
		-i configure Makefile || die

	# we'll strip the binaries ourselves
	sed -e '/^[[:space:]]*strip[[:space:]]*=/d' -i Cargo.toml || die

	sed -e '/^PLUGINS += \$(RUST_PLUGINS)$/arust-plugins : $(RUST_PLUGINS)\' \
		-e '.PHONY : rust-plugins' \
		-i plugins/Makefile || die

	# our VERSION="${MyPVR}" confuses is_released_version()
	[[ ${PV} != *([.[:digit:]]) ]] ||
		sed -ne '/^bool is_released_version(void)/{a { return true; }
			p;:x;n;/^}$/d;bx};p' -i common/version.c || die

	# save our SSDs! ("cp" -> "cp -l")
	local shopt_pop=$(shopt -p globstar)
	shopt -s globstar
	sed -e 's/\bcp\b/cp -l/g' -i -- **/Makefile || die
	${shopt_pop}

	# don't require running in a Git worktree
	rm conftest.py || die

	use python && distutils-r1_src_prepare
}

src_configure() {
	local BUNDLED_LIBS="external/build-${CHOST}/libjsmn.a"
	. "${FILESDIR}/compat_vars.bash"
	CLIGHTNING_MAKEOPTS=(
		V=1
		VERSION="${MyPVR}"
		DISTRO=Gentoo
		DEFAULT_TARGETS=
		COVERAGE=
		DOC_DATA=
		BOLTDIR="${WORKDIR}/does_not_exist"
		COMPAT_CFLAGS="${COMPAT_CFLAGS[*]}"
		LIBSODIUM_HEADERS=
		LIBWALLY_HEADERS=
		LIBSECP_HEADERS=
		LIBBACKTRACE_HEADERS=
		EXTERNAL_LIBS="${BUNDLED_LIBS}"
		EXTERNAL_INCLUDE_FLAGS="-I external/jsmn/ -I external/gheap/ $("$(tc-getPKG_CONFIG)" --cflags libsodium wallycore libsecp256k1_zkp)"
		EXTERNAL_LDLIBS="${BUNDLED_LIBS} $("$(tc-getPKG_CONFIG)" --libs libsodium wallycore libsecp256k1_zkp) -lbacktrace"
		docdir="/usr/share/doc/${PF}"
	)

	use man || CLIGHTNING_MAKEOPTS+=(
		MANPAGES=
	)

	use test || CLIGHTNING_MAKEOPTS+=(
		ALL_TEST_PROGRAMS=
		ALL_FUZZ_TARGETS=
	)
	use test-full || CLIGHTNING_MAKEOPTS+=(
		DEVTOOLS=
	)

	use postgres || local -x POSTGRES_INCLUDE= POSTGRES_LDLIBS=
	use sqlite || local -x SQLITE3_CFLAGS= SQLITE3_LDLIBS=

	use rust && CLIGHTNING_MAKEOPTS+=(
		RUST_PROFILE=release
		CARGO_OPTS=--profile=release
		CLN_RPC_EXAMPLES=
		CLN_GRPC_EXAMPLES=
		CLN_PLUGIN_EXAMPLES=
		CLNREST_EXAMPLES=
	)

	use debug && append-cflags -Wno-error

	python_need='mako' python_setup
	local -x PYTEST="${PYTHON} -m pytest"  # avoid calling uv
	edo ./configure \
		CC="$(tc-getCC)" \
		CONFIGURATOR_CC="$(tc-getBUILD_CC)" \
		$(usex debug '' CDEBUGFLAGS=) \
		COPTFLAGS= \
		--prefix="${EPREFIX}"/usr \
		$(use_enable debug{,build}) \
		--disable-compat \
		--disable-valgrind \
		--disable-static \
		--disable-coverage \
		--disable-address-sanitizer \
		--disable-ub-sanitize \
		--disable-fuzzing \
		$(use_enable rust)

	use python && distutils-r1_src_configure
	use rust && cargo_src_configure
}

src_compile() {
	python_need='mako' python_setup
	emake "${CLIGHTNING_MAKEOPTS[@]}"

	if use doc ; then
		# dev-python/mkdocs is no longer supported (#971358)
		if use python ; then
			python_need='sphinx'
			python_setup
		fi
	fi

	use python && distutils-r1_src_compile

	if use rust ; then
		# these sources weren't generated above because we set DEFAULT_TARGETS=
		emake "${CLIGHTNING_MAKEOPTS[@]}" cln-{,g}rpc-all
		cargo_src_compile
		use test && cargo_src_test --no-run
		# link all the Cargo-built plugins into the plugins directory
		emake "${CLIGHTNING_MAKEOPTS[@]}" rust-plugins
	fi
}

python_compile() {
	python_foreach_subdir python_compile_subdir
}

python_compile_subdir() {
	distutils-r1_python_compile
	rm -f -- "${BUILD_DIR}/install$(python_get_sitedir)/pyln"{,/spec}/{__init__.py,__pycache__/__init__.*.pyc} || die
}

python_compile_all() {
	use doc && python_foreach_subdir python_compile_subdir_docs
}

python_compile_subdir_docs() {
	local -a HTML_DOCS
	[[ -f docs/conf.py ]] && build_sphinx docs
}

src_test() {
	# disable flaky bitcoin/test/run-secret_eq_consttime
	local -x SLOW_MACHINE=1
	emake "${CLIGHTNING_MAKEOPTS[@]}" check-units

	use python && distutils-r1_src_test
	use rust && cargo_src_test

	if use test-full ; then
		local python_need='test-full'
		python_setup
		local EPYTEST_XDIST=1
		# double up, as these tests are surprisingly ineffective at saturating the CPU
		[[ -v EPYTEST_JOBS ]] || local -i EPYTEST_JOBS="$(makeopts_jobs)*2"
		local -a pythonpath
		mapfile -t pythonpath <<<"$(readlink -e -- "${PYTHON_SUBDIRS[@]}" contrib/pyln-{grpc-proto,testing})"
		local -x PYTHONPATH="$(IFS=: ; printf '%s' "${pythonpath[*]}")" RUST_PROFILE=release
		TEST_DIR="${T}" epytest tests
	fi
}

python_test() {
	epytest "${PYTHON_SUBDIRS[@]}"
}

python_install_all() {
	python_foreach_subdir python_install_subdir_docs
}

python_install_subdir_docs() {
	local shopt_pop=$(shopt -p nullglob)
	shopt -s nullglob
	local -a docs=( README* )
	${shopt_pop}
	docinto "${PWD##*/}"
	(( ${#docs[@]} )) && dodoc "${docs[@]}"
	use doc && [[ -d docs/_build/html ]] && dodoc -r docs/_build/html
}

src_install() {
	emake "${CLIGHTNING_MAKEOPTS[@]}" DESTDIR="${D}" install
	einstalldocs

	insinto /etc/lightning
	newins "${FILESDIR}/lightningd-26.06.conf" lightningd.conf
	fowners :lightning /etc/lightning/lightningd.conf
	fperms 0640 /etc/lightning/lightningd.conf

	newinitd "${FILESDIR}/init.d-lightningd" lightningd
	newconfd "${FILESDIR}/conf.d-lightningd" lightningd

	newbashcomp contrib/lightning-cli.bash-completion lightning-cli

	use python && distutils-r1_src_install

	insinto "/etc/portage/savedconfig/${CATEGORY}"
	newins compat.vars "${PN}"
}

pkg_preinst() {
	if [[ -e ${EROOT%/}/etc/lightning/config && ! -e ${EROOT%/}/etc/lightning/lightningd.conf ]] ; then
		elog "Moving your /etc/lightning/config to /etc/lightning/lightningd.conf"
		mv --no-clobber -- "${EROOT%/}/etc/lightning/"{config,lightningd.conf}
	fi
}

pkg_postinst() {
	efmt -su elog <<-EOF
		To use lightning-cli with the /etc/init.d/lightningd service:
		 - Add your user(s) to the 'lightning' group.
		 - Symlink ~/.lightning to /var/lib/lightning.
	EOF

	if ver_replacing -lt 25.05 ; then
		efmt ewarn <<-EOF
			Due to experimental protocol upgrades, --experimental-splicing is
			incompatible with previous CLN versions. You will not be able to
			reestablish channels with older nodes at all if this is enabled! If you
			have CLN peers with the experimental splicing feature, consider disabling
			this option until they upgrade to support the latest draft spec.
		EOF
	fi
}