# Copyright 2026 Nadeŭka <me+oss@nadevko.cc>
# Distributed under the terms of the GNU General Public License v2
EAPI=8

inherit desktop optfeature pax-utils unpacker xdg

DESCRIPTION='Official management and launcher tool for Unity Engine'
HOMEPAGE=https://unity.com/hub
BASE_URI=https://hub-dist.unity3d.com/artifactory/hub-debian-prod-local/pool/main/u/unity
SRC_URI="
	amd64? ( ${BASE_URI}/unityhub_amd64/UnityHubSetup-${PV}-amd64.deb -> ${P}-amd64.deb )
	arm64? ( ${BASE_URI}/unityhub_arm64/UnityHubSetup-${PV}-arm64.deb -> ${P}-arm64.deb )
"
S="${WORKDIR}"

LICENSE='
	Apache-2.0 Artistic-2 BSD BSD-2 BZIP2 curl CyberNeko icu ISC LGPL-2.1 MIT
	MPL-2.0 MS-EULA Naumen openssl public-domain Unity-Companion
	Unity-Editor-Software Unity-Package-Distribution Unity-ToS Xnet ZLIB
'
SLOT=0
KEYWORDS='~amd64'

IUSE='apparmor bwrap +telemetry'
RESTRICT='bindist mirror strip'

QA_PREBUILT="opt/${PN}/*"

RDEPEND='
	app-accessibility/at-spi2-core:2
	app-alternatives/cpio
	app-arch/tar
	app-arch/unzip
	app-arch/zip
	app-crypt/libsecret
	cli-dcc/unity-cli-bin
	dev-libs/expat
	dev-libs/glib:2
	dev-libs/nspr
	dev-libs/nss
	media-libs/alsa-lib
	media-libs/fontconfig
	media-libs/freetype
	media-libs/mesa[gbm(+)]
	net-print/cups
	sys-apps/dbus
	sys-apps/util-linux
	x11-libs/cairo
	x11-libs/gtk+:3
	x11-libs/libdrm
	x11-libs/libnotify
	x11-libs/libX11
	x11-libs/libxcb
	x11-libs/libXcomposite
	x11-libs/libXcursor
	x11-libs/libXdamage
	x11-libs/libXext
	x11-libs/libXfixes
	x11-libs/libXi
	x11-libs/libxkbcommon
	x11-libs/libXrandr
	x11-libs/libXrender
	x11-libs/libXScrnSaver
	x11-libs/libXtst
	x11-libs/pango
	x11-misc/xdg-utils
	bwrap? ( sys-apps/bubblewrap )
'

src_unpack() {
	unpack_deb ${A}
}

src_prepare() {
	default

	local dest="/opt/${PN}"

	# Remove unused LTTng tracepoint provider to fix unresolved soname (liblttng-ust.so.0)
	rm usr/lib/unityhub/UnityLicensingClient_V1/libcoreclrtraceptprovider.so || die

	# Remove embedded unity-cli binary (replaced by symlink to unity-cli-bin)
	rm usr/lib/unityhub/resources/unity || die

	# Remove redundant raw license dumps (Portage manages licenses; keep only resources/licenses.html for Hub UI)
	rm usr/lib/unityhub/LICENSES.chromium.html || die
	rm usr/lib/unityhub/UnityLicensingClient_V1/LICENSE.md || die
	rm usr/lib/unityhub/UnityLicensingClient_V1/"Third Party Notices.md" || die

	# Disable built-in auto updater
	rm usr/lib/unityhub/resources/{app-update.yml,package-type} || die

	# Binary-patch app.asar: hard-disable auto updates and force compliance with XDG_DATA_HOME
	sed -i -e 's/AUTO_UPDATE: true/AUTO_UPDATE: 0   /g' \
	       -e 's|\${os.homedir()}/.local/share|\${process.env.UNITY_DATADIR}|g' \
	       usr/lib/unityhub/resources/app.asar || die

	# Patch launcher script to point to install dir and export UNITY_DATADIR
	sed -e "s|^SCRIPT_DIR=.*|SCRIPT_DIR='${EPREFIX}${dest}'|" \
	    -e '1a export UNITY_DATADIR="${XDG_DATA_HOME:-${HOME}/.local/share}"' \
	    -i usr/bin/unityhub || die

	# Match desktop icon, binary name, and prefer discrete GPU on hybrid setups
	sed -e "s|^Exec=.*|Exec=unityhub %U|" \
	    -e "s|^Icon=.*|Icon=unityhub|" \
	    -e '$a PrefersNonDefaultGPU=true' \
	    -i usr/share/applications/unityhub.desktop || die

	# Patch AppArmor profile path to match Gentoo install location
	if use apparmor; then
		sed -e "s|/usr/lib/unityhub/unityhub-bin|${EPREFIX}${dest}/unityhub-bin|" \
			-i usr/lib/unityhub/resources/apparmor-profile || die
	fi

	# Disable crash reporter in launcher script if USE="-telemetry"
	if ! use telemetry; then
		sed -e 's|LAUNCH_ARGS=(|LAUNCH_ARGS=( "--disable-crash-reporter" |' \
			-i usr/bin/unityhub || die
	fi

	# Generate bubblewrap launcher wrapper if enabled
	if use bwrap; then
		sed -e "s|@EXEC@|${EPREFIX}${dest}/unityhub|g" \
			"${FILESDIR}"/bwrap.sh > "${T}"/unityhub || die
	fi
}

src_install() {
	local dest=/opt/${PN}

	# bins & wrappers (only single canonical unityhub binary)
	if use bwrap; then
		dobin "${T}"/unityhub
	else
		dobin usr/bin/unityhub
	fi

	# configs
	if use apparmor; then
		insinto /etc/apparmor.d
		newins usr/lib/unityhub/resources/apparmor-profile unityhub
	fi
	rm usr/lib/unityhub/resources/apparmor-profile || die

	if ! use telemetry; then
		newenvd - 90${PN} <<-EOF
			DOTNET_CLI_TELEMETRY_OPTOUT=1
			OTEL_SDK_DISABLED=true
			UNITY_NO_CLI_INVOKED_TELEMETRY=1
		EOF
	fi

	# desktop
	domenu usr/share/applications/unityhub.desktop

	# icons
	local size
	for size in 16 24 32 48 64 128 256 512; do
		newicon -s ${size} \
			usr/share/icons/hicolor/${size}x${size}/apps/unityhub.png \
			unityhub.png
	done

	# mime
	insinto /usr/share/metainfo
	doins usr/share/metainfo/com.unity3d.unityhub.metainfo.xml

	# /opt installation
	dodir "${dest}"
	cp -a usr/lib/unityhub/* "${ED}${dest}" || die
	dosym -r /usr/bin/unity "${dest}/resources/unity"

	# permissions & security
	pax-mark m "${ED}${dest}"/{unityhub-bin,chrome_crashpad_handler}
	pax-mark m "${ED}${dest}"/UnityLicensingClient_V1/{Unity.Licensing.Client,createdump}
}

pkg_postinst() {
	xdg_pkg_postinst

	if use bwrap; then
		elog 'Bubblewrap sandboxing is ENABLED. Unity Hub has restricted access to $HOME.'
		elog 'Only ~/Unity, ~/.config/Unity*, ~/.local/share/unity3d, and directories passed'
		elog 'via CLI arguments are exposed.'
	fi

	if ! use telemetry; then
		elog "Telemetry, OpenTelemetry SDK, and crash reporting have been disabled via USE='-telemetry'."
	fi

	optfeature_header 'Unity Editor instances installed through the Hub may require:'
	optfeature 'OpenGL Utility Library (GLU)' media-libs/glu
	optfeature '7-Zip package unpacker' app-arch/p7zip
	optfeature "Editors before Unity's libxml2 fix" dev-libs/libxml2-compat:2
	optfeature 'Editors that still link OpenSSL 1.1' dev-libs/openssl-compat:1.1.1
}