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

EAPI=8

inherit systemd unpacker

# upstream tags release candidates as v0.41.0-rc1
MY_PV="${PV/_rc/-rc}"

DESCRIPTION="Ollama - get up and running with large language models."
HOMEPAGE="https://ollama.com/"
# amd64 keeps the old distfile name, so existing users don't download it again;
# arm64 needs its own name, otherwise both tarballs fight over one Manifest entry
SRC_URI="
	amd64? ( https://github.com/ollama/ollama/releases/download/v${MY_PV}/ollama-linux-amd64.tar.zst -> ${P}.tar.zst )
	arm64? ( https://github.com/ollama/ollama/releases/download/v${MY_PV}/ollama-linux-arm64.tar.zst -> ${P}-arm64.tar.zst )
"
S="${WORKDIR}"

LICENSE="MIT"
SLOT="0"
KEYWORDS="~amd64 ~arm64"
IUSE="+systemd cpuonly"
REQUIRED_USE="cpuonly? ( systemd )"

# upstream prebuilt binaries
RESTRICT="strip"
QA_PREBUILT="*"
REQUIRES_EXCLUDE="libamdhip64.so.6 libhipblas.so.2 librocblas.so.4"

RDEPEND="
	acct-user/genai
	acct-group/genai
	acct-group/render
	acct-group/video
"
BDEPEND="$(unpacker_src_uri_depends)"

src_install() {
	dodir /usr
	cp -R "${S}"/. "${ED}"/usr/ || die "install failed"

	if use systemd; then
		if use cpuonly; then
			systemd_newunit "${FILESDIR}"/ollama-cpu.service ollama.service
		else
			systemd_newunit "${FILESDIR}"/ollama.service ollama.service
			# extra instances, e.g. one per GPU: ollama@<name>.service
			# reads its settings from /etc/ollama/<name>.conf
			systemd_newunit "${FILESDIR}"/ollama_at.service 'ollama@.service'
			insinto /etc/ollama
			newins "${FILESDIR}"/ollama-instance.conf.example instance.conf.example
		fi
	fi
}

pkg_postinst() {
	if use systemd; then
		elog "Reload systemd and restart Ollama if it was running:"
		elog "  systemctl daemon-reload && systemctl restart ollama.service"
		if ! use cpuonly; then
			elog
			elog "To run extra instances (e.g. one per GPU), copy"
			elog "/etc/ollama/instance.conf.example to /etc/ollama/<name>.conf,"
			elog "adjust it and run: systemctl enable --now ollama@<name>.service"
		fi
	fi
}