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

EAPI=8

inherit cmake flag-o-matic xdg

MY_PN="UZDoom"
DESCRIPTION="Modder-friendly hardware-accelerated source port of the DOOM engine"
HOMEPAGE="https://zdoom.org"
SRC_URI="https://github.com/${MY_PN}/${MY_PN}/archive/refs/tags/${PV}.tar.gz -> ${P}.tar.gz"
S="${WORKDIR}/${MY_PN}-${PV}"

LICENSE="Apache-2.0 BSD BZIP2 GPL-3 LGPL-2.1+ LGPL-3 MIT
	non-free? ( Activision ChexQuest3 DOOM-COLLECTORS-EDITION freedist WidePix )"
SLOT="0"
KEYWORDS="~amd64 ~arm64 ~ppc64"
IUSE="debug gles2 gtk +non-free openmp +swr telemetry vulkan"

DEPEND="
	app-arch/bzip2:=
	media-libs/libjpeg-turbo:0=
	media-libs/libsdl2[gles2?,opengl,vulkan?]
	media-libs/libvpx:=
	media-libs/libwebp:=
	media-libs/openal
	>=media-libs/zmusic-1.1.14
	virtual/zlib:=
	gtk? ( x11-libs/gtk+:3 )
"
RDEPEND="
	${DEPEND}
	!games-fps/gzdoom
"
BDEPEND="
	virtual/pkgconfig
"

PATCHES=(
	"${FILESDIR}"/${P}-build-nonfree.patch
)

src_prepare() {
	rm -rf docs/licenses libraries/{bzip2,jpeg,zlib} || die
	cmake_src_prepare

	cat <<-EOF > "${S}/src/gitinfo.h" || die
	// 0
	// The above line prevents UpdateRevision.cmake from replacing this file.
	// This file was generated by the Gentoo ebuild.

	#define GIT_DESCRIPTION "${PV}"
	#define GIT_HASH "0"
	#define GIT_TIME ""
	EOF

	# Split assets into nonfree directory. This is currently being upstreamed.
	# https://github.com/UZDoom/UZDoom/pull/813
	cd wadsrc_extra || die
	mkdir -p nonfree/sounds || die
	mv ../wadsrc/static/sounds/dssecret.flac nonfree/sounds/ || die
	cd static || die
	find filter ! -path "filter/harmony/*" \( -name font.inf -o -name "*.lmp" -o -name "*.png" \) |
		gtar --verbatim-files-from --remove-files -cT - | gtar -xC ../nonfree || die
}

src_configure() {
	# https://bugs.gentoo.org/858749
	filter-lto
	append-flags -fno-strict-aliasing

	local mycmakeargs=(
		-DBUILD_NONFREE=$(usex non-free)
		-DBUILD_SHARED_LIBS=OFF
		-DINSTALL_DOCS_PATH="${EPREFIX}/usr/share/doc/${PF}"
		-DINSTALL_PK3_PATH="${EPREFIX}/usr/share/doom"
		-DINSTALL_SOUNDFONT_PATH="${EPREFIX}/usr/share/doom"
		-DDYN_OPENAL=OFF
		-DNO_GTK=$(usex !gtk)
		-DNO_OPENAL=OFF
		-DHAVE_VULKAN=$(usex vulkan)
		-DHAVE_GLES2=$(usex gles2)
		-DNO_OPENMP=$(usex !openmp)
		-DZDOOM_ENABLE_SWR=$(usex swr)
		-DSEND_ANON_STATS=$(usex telemetry)
	)

	use debug || append-cppflags -DNDEBUG
	cmake_src_configure
}

pkg_postinst() {
	xdg_pkg_postinst

	if ! use non-free ; then
		ewarn
		ewarn "${MY_PN} has been installed without non-free components. Commercial"
		ewarn "games should still run, but the experience may be suboptimal."
		ewarn
	fi
}