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

EAPI=8

inherit eapi9-ver go-module linux-info systemd udev

GOLANG_X_SYS_PV=0.18.0

DESCRIPTION="XenServer / XCP-ng guest agent reporting guest metrics to the host"
HOMEPAGE="https://github.com/xenserver/xe-guest-utilities"
SRC_URI="
	https://github.com/xenserver/xe-guest-utilities/archive/v${PV}.tar.gz
		-> ${P}.tar.gz
	https://github.com/golang/sys/archive/v${GOLANG_X_SYS_PV}.tar.gz
		-> golang-x-sys-${GOLANG_X_SYS_PV}.tar.gz
"

LICENSE="BSD-2"
# Dependent licenses
LICENSE+=" BSD"
SLOT="0"
KEYWORDS="~amd64 ~x86"
IUSE="xenstore"

RDEPEND="
	sys-apps/iproute2
	xenstore? ( !app-emulation/xen-tools )
"

CONFIG_CHECK="~XEN_COMPAT_XENFS ~XENFS"

src_unpack() {
	go-module_src_unpack

	# Upstream ships vendor/modules.txt, but not the vendored module
	mkdir -p "${S}"/vendor/golang.org/x || die
	mv "${WORKDIR}"/sys-${GOLANG_X_SYS_PV} "${S}"/vendor/golang.org/x/sys || die
	# Record the module's Go version (from its go.mod) like 'go mod vendor'
	# does, otherwise it is compiled as go1.16 and fails
	sed -i -e 's/^## explicit$/## explicit; go 1.18/' \
		"${S}"/vendor/modules.txt || die
}

src_prepare() {
	default

	# Normally substituted by upstream's Makefile, which requires git
	sed -i \
		-e "s/@PRODUCT_MAJOR_VERSION@/$(ver_cut 1)/" \
		-e "s/@PRODUCT_MINOR_VERSION@/$(ver_cut 2)/" \
		-e "s/@PRODUCT_MICRO_VERSION@/$(ver_cut 3)/" \
		-e "s/@NUMERIC_BUILD_NUMBER@/0/" \
		guestmetric/guestmetric_linux.go || die

	# Make the #!/bin/sh script POSIX sh compatible
	sed -i \
		-e 's/^\(\s*\)source /\1. /' \
		-e 's/\[ "${distro}" == "rhel" \]/[ "${distro}" = "rhel" ]/' \
		mk/xe-linux-distribution || die

	sed -i -e 's:/usr/share/oem/xs/:/usr/sbin/:g' \
		mk/xe-linux-distribution.service || die
}

src_compile() {
	mkdir -p bin || die
	ego build -o bin/xe-daemon ./xe-daemon
	if use xenstore; then
		ego build -o bin/xenstore ./xenstore
	fi
}

src_test() {
	# TestCollector requires running inside a Xen guest. go vet trips over
	# a non-constant format string in xenstore/xenstore.go.
	ego test -vet=off -skip TestCollector ./...
}

src_install() {
	dosbin bin/xe-daemon mk/xe-linux-distribution
	newinitd "${FILESDIR}"/xe-daemon.initd xe-daemon
	systemd_dounit mk/xe-linux-distribution.service
	udev_newrules mk/xen-vcpu-hotplug.rules 10-xen-vcpu-hotplug.rules

	if use xenstore; then
		dobin bin/xenstore
		local cmd
		for cmd in chmod exists list ls read rm watch write; do
			dosym xenstore /usr/bin/xenstore-${cmd}
		done
	fi

	einstalldocs
}

pkg_postinst() {
	udev_reload

	# Versions before 10 did not install a systemd unit
	if [[ -z ${REPLACING_VERSIONS} ]] || ver_replacing -lt 10; then
		elog "To start the guest agent at boot, run"
		elog "  rc-update add xe-daemon boot"
		elog "or, with systemd,"
		elog "  systemctl enable xe-linux-distribution.service"
	fi
}

pkg_postrm() {
	udev_reload
}
