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

# Autogenerated by pycargoebuild 0.15.0

EAPI=8

CRATES="
	glob@0.3.3
	libc@0.2.178
"

inherit pam cargo

DESCRIPTION="A memory safe implementation of sudo and su."
HOMEPAGE="https://github.com/trifectatechfoundation/sudo-rs"
SRC_URI="
	https://github.com/trifectatechfoundation/${PN}/archive/refs/tags/v${PV}.tar.gz -> ${P}.tar.gz
	${CARGO_CRATE_URIS}
"

LICENSE="|| ( Apache-2.0 MIT )"
# Dependent crate licenses
LICENSE+=" || ( Apache-2.0 MIT )"
SLOT="0"
KEYWORDS="~amd64 ~arm64"

IUSE="pam su system-names"

RDEPEND="
	system-names? (
		!app-admin/sudo
		su? (
			!sys-apps/util-linux[su]
			!sys-apps/shadow[su]
			pam? ( sys-apps/util-linux[pam] )
		)
	)
"

QA_FLAGS_IGNORED="usr/bin/.*"

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

PATCHES=(
	# disable tests that require root access
	"${FILESDIR}/sudo-rs-0.2.8-tests.patch"
)

src_prepare() {
	local -a targets
	local target

	if ! use system-names; then
		find "${S}" -name '*.rs' -or -name 'Cargo.toml' \
			| xargs sed -r -e 's:"(sudo|visudo|su|su-l)":"\1-rs": ; s:"sudo-i":"sudo-rs-i":' -i || die

		readarray -t targets < <(find src/bin -name '*.rs')

		for target in "${targets[@]}"; do
			mv "${target}" "${target//.rs/-rs.rs}" || die
		done

	elif ! use su; then
		find "${S}" -name '*.rs' -or -name 'Cargo.toml' \
			| xargs sed -r -e 's:"(su|su-l)":"\1-rs":' -i || die

		readarray -t targets < <(find src/bin -name '*.rs' -and -not -name '*sudo*')

		for target in "${targets[@]}"; do
			rm "${target}" || die
		done
	fi

	default
}

src_install() {
	cargo_src_install

	local ext=$(usex system-names '' '-rs')
	local su_ext=$(usex su "${ext}" '-rs')
	local -a binaries=( sudo${ext} )
	use su && binaries+=( su${su_ext} )

	dodoc "${DOCS[@]}"

	local man dest
	for man in docs/man/*.?.man; do
		dest="${man##*/}"
		dest="${dest%.man}"
		if [[ ${dest#.*} == su.* ]]; then
			dest="${dest/./${su_ext}.}"
		else
			dest="${dest/./${ext}.}"
		fi
		newman "${man}" "${dest}"
	done

	fperms 4755 $(printf -- '/usr/bin/%s\n' "${binaries[@]}")

	insinto /etc
	doins "${FILESDIR}"/sudoers-rs

	keepdir /etc/sudoers.d

	if use pam; then
		pamd_mimic system-auth sudo${ext} auth account session
		pamd_mimic system-auth sudo${ext}-i auth account session

		if ! use system-names && use su; then
			pamd_mimic system-auth su${ext}-l auth account session
		fi
	fi
}
