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

EAPI=8

MY_PN=${PN%-bin}
MY_URI="https://github.com/carthage-software/mago/releases/download/${PV}/${MY_PN}-${PV}"

DESCRIPTION="Prebuilt linter, formatter and static analyzer for PHP, written in Rust"
HOMEPAGE="
	https://mago.carthage.software/
	https://github.com/carthage-software/mago
"
SRC_URI="
	amd64? (
		elibc_glibc? ( ${MY_URI}-x86_64-unknown-linux-gnu.tar.gz )
		elibc_musl? ( ${MY_URI}-x86_64-unknown-linux-musl.tar.gz )
	)
	arm64? (
		elibc_glibc? ( ${MY_URI}-aarch64-unknown-linux-gnu.tar.gz )
		elibc_musl? ( ${MY_URI}-aarch64-unknown-linux-musl.tar.gz )
	)
"
S="${WORKDIR}"

# Mago and its Rust dependencies are statically included.
# These licenses match the source package.
LICENSE="|| ( Apache-2.0 MIT )"
LICENSE+="
	Apache-2.0 BSD BSD-2 Boost-1.0 CC0-1.0 CDLA-Permissive-2.0 ISC MIT MPL-2.0
	Unicode-3.0 ZLIB
"
SLOT="0"
KEYWORDS="-* ~amd64 ~arm64"
REQUIRED_USE="|| ( elibc_glibc elibc_musl )"

# The musl builds are static; the glibc builds link libgcc_s and glibc.
RDEPEND="
	!dev-util/mago
	elibc_glibc? (
		|| (
			llvm-runtimes/libgcc
			sys-devel/gcc:*
		)
		>=sys-libs/glibc-2.18
	)
"
BDEPEND="dev-util/patchelf"

QA_PREBUILT="usr/libexec/${PN}/mago"

src_install() {
	cd "${MY_PN}-${PV}"-* || die
	# Upstream's builds keep a RUNPATH into the build machine's Rust toolchain.
	patchelf --remove-rpath mago || die
	exeinto /usr/libexec/${PN}
	doexe mago
	# Portage owns the binary: the wrapper keeps self-update from overwriting it.
	# TODO: drop when upstream adds a build switch for self-update:
	# https://github.com/carthage-software/mago/issues/2884
	newbin "${FILESDIR}"/mago-wrapper mago
	dodoc README.md
}