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

EAPI=8

inherit desktop xdg

# Upstream suffixes each release archive with its build date.
GHIDRA_DATE="20261016"
MY_P="ghidra_${PV}_PUBLIC"

DESCRIPTION="Software reverse engineering framework (official NSA release build)"
HOMEPAGE="https://ghidra-sre.org/ https://github.com/NationalSecurityAgency/ghidra"
SRC_URI="https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_${PV}_build/${MY_P}_${GHIDRA_DATE}.zip"

S="${WORKDIR}/${MY_P}"

LICENSE="Apache-2.0 Apache-2.0-with-LLVM-exceptions BSD BSD-2 CC-BY-2.5 GPL-2
	GPL-2-with-classpath-exception JDOM LGPL-2.1 LGPL-3 MIT MPL-2.0 POSTGRESQL
	PSF-2 public-domain ZLIB"
SLOT="0"
KEYWORDS="~amd64"
RESTRICT="mirror strip"

RDEPEND=">=virtual/jdk-21:*"
BDEPEND="app-arch/unzip"

QA_PREBUILT="opt/ghidra/*"

src_prepare() {
	default

	# Only the linux_x86_64 natives can run here.
	local os
	for os in linux_arm_64 mac_arm_64 mac_x86_64 win_x86_32 win_x86_64; do
		find . -depth -type d -path "*/os/${os}" -exec rm -r {} + || die
	done
	rm -r Ghidra/Features/FileFormats/data/sevenzipnativelibs/{Mac-x86_64,Windows-amd64} || die
	find . -type f -name '*.bat' -delete || die
}

src_install() {
	dodir /opt/ghidra
	cp -a . "${ED}"/opt/ghidra/ || die

	# The launchers resolve their own location with readlink -f.
	dosym ../../opt/ghidra/ghidraRun /usr/bin/ghidra
	dosym ../../opt/ghidra/support/analyzeHeadless /usr/bin/ghidra-analyzeHeadless

	newicon docs/images/GHIDRA_1.png ghidra.png
	make_desktop_entry ghidra Ghidra ghidra "Development;Debugger;"
}

pkg_postinst() {
	xdg_pkg_postinst

	elog "Ghidra needs a full JDK, version 21 or newer."
	elog "It uses JAVA_HOME when set, otherwise the java found in PATH"
	elog "(see 'eselect java-vm')."
	elog ""
	elog "Tools that drive Ghidra headless (REA, scripts) should use:"
	elog "  GHIDRA_INSTALL_DIR=${EPREFIX}/opt/ghidra"
}