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

EAPI=8

PYTHON_COMPAT=( python3_{12..15} )

inherit git-r3 linux-info python-single-r1 systemd

DESCRIPTION="Run emerge on all CPU cores with a lower clock cap to keep a laptop cool"
HOMEPAGE="https://github.com/vitaly-zdanevich/emerge-cool"
EGIT_REPO_URI="https://github.com/vitaly-zdanevich/${PN}.git"

LICENSE="MIT"
SLOT="0"
REQUIRED_USE="${PYTHON_REQUIRED_USE}"

RDEPEND="
	${PYTHON_DEPS}
	sys-apps/portage
	sys-apps/util-linux
"
BDEPEND="${PYTHON_DEPS}"

pkg_setup() {
	CONFIG_CHECK="~CPU_FREQ"
	if use amd64; then
		CONFIG_CHECK+=" ~X86_MSR"
	fi
	linux-info_pkg_setup
	python-single-r1_pkg_setup
}

src_test() {
	tests/turbo-activation-ratio.sh || die "turbo-activation-ratio tests failed"

	if [[ ${EUID} -eq 0 ]]; then
		ewarn "Skipping the emerge-cool tests: they must run as a regular user (FEATURES=userpriv)"
		return
	fi
	# The tests run emerge-cool as fake root: unshare -r writes /proc/self/uid_map, seen by sandbox as /proc/PID
	addwrite /proc
	if ! unshare -r true 2> /dev/null; then
		ewarn "Skipping the emerge-cool tests: they need unprivileged user namespaces (unshare -r)"
		return
	fi
	tests/emerge-cool.sh || die "emerge-cool tests failed"
}

src_install() {
	dosbin emerge-cool
	insinto /etc
	doins emerge-cool.conf

	python_scriptinto /usr/sbin
	python_doscript turbo-activation-ratio
	newinitd openrc/turbo-activation-ratio turbo-activation-ratio
	systemd_dounit systemd/turbo-activation-ratio.service
	exeinto /usr/lib/elogind/system-sleep
	doexe system-sleep/turbo-activation-ratio
	: "$(systemd_get_sleepdir)"
	exeinto "${_#"${EPREFIX}"}"
	doexe system-sleep/turbo-activation-ratio

	einstalldocs
}

pkg_postinst() {
	elog "Run emerge-cool instead of emerge, with MAKEOPTS using all threads, for example:"
	elog "  MAKEOPTS='--jobs 8' emerge-cool --ask www-client/firefox"
	elog "Tune the clock cap in /etc/emerge-cool.conf."
	elog
	elog "If the CPUs run above the cap during a build, enable turbo-activation-ratio at boot:"
	elog "  OpenRC:  rc-update add turbo-activation-ratio boot"
	elog "  systemd: systemctl enable turbo-activation-ratio.service"
}