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

# creating vendor bundle:
# >> V=1.17.0
# >> git clone --depth 1 -b v${V} \
# >>   https://github.com/grafana/alloy /tmp/alloy
# >> cd /tmp/alloy && go mod vendor
# >> mkdir -p internal/web/ui/dist
# >> touch internal/web/ui/dist/index.html
# >> cd collector \
# >>   && BUILDER_VERSION=v0.139.0 go generate \
# >>   && go mod vendor && cd ..
# >> mkdir -p alloy-${V}/collector
# >> mv vendor alloy-${V}/vendor
# >> mv collector/vendor alloy-${V}/collector/vendor
# >> tar -caf alloy-${V}-vendor.tar.xz alloy-${V}

EAPI=8

inherit systemd

DESCRIPTION="OpenTelemetry Collector distribution \
with built-in Prometheus pipelines."
HOMEPAGE="https://github.com/grafana/alloy"
SRC_URI="https://github.com/grafana/${PN}/archive/v${PV}.tar.gz
	-> ${P}.tar.gz
	https://lab.retarded.farm/distfiles/${P}-vendor.tar.xz"

LICENSE="Apache-2.0"
SLOT="0"
KEYWORDS="~amd64"

IUSE="systemd"

RESTRICT="mirror strip"

RDEPEND="acct-group/grafana
	acct-user/${PN}"
DEPEND="${RDEPEND}
	>=dev-lang/go-1.26.4
	sys-apps/systemd"

src_prepare() {
	default
	# UI embed needs at least a dummy file
	mkdir -p "${S}/internal/web/ui/dist" || die
	touch "${S}/internal/web/ui/dist/index.html" || die
}

src_compile() {
	local VPREFIX="github.com/grafana/${PN}/internal/build"
	local VPREFIXSYNTAX
	VPREFIXSYNTAX="github.com/grafana/${PN}/syntax/internal/stdlib"
	local BUILD_DATE
	BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

	local GO_LDFLAGS="-s -w \
		-X ${VPREFIX}.Version=v${PV} \
		-X ${VPREFIXSYNTAX}.Version=v${PV} \
		-X ${VPREFIX}.Revision=v${PV} \
		-X ${VPREFIX}.BuildUser=portage@gentoo \
		-X ${VPREFIX}.BuildDate=${BUILD_DATE} \
		-X ${VPREFIX}.Branch=v${PV}"

	einfo "Building alloy..."
	cd "${S}/collector" || die
	CGO_ENABLED=1 go build -x \
		-ldflags "${GO_LDFLAGS}" \
		-tags "gore2regex netgo promtail_journal_enabled" \
		-mod vendor \
		-o "${S}/build/alloy" . || die
}

src_install() {
	dobin "${S}/build/alloy"

	newconfd "${FILESDIR}/alloy.confd" "alloy"
	newinitd "${FILESDIR}/alloy.initd" "alloy"
	use systemd && systemd_newunit \
		"${FILESDIR}"/alloy.service alloy.service

	insinto "/etc/alloy"
	newins "${S}/example-config.alloy" "config.alloy"
	keepdir "/etc/alloy"
	keepdir "/var/lib/alloy"
	fowners alloy:grafana "/etc/alloy"
	fowners alloy:grafana "/var/lib/alloy"
}