# Copyright 2026 Haelwenn (lanodan) Monnier <contact@hacktivis.me>
# Distributed under the terms of the GNU General Public License v2

EAPI=8


if [[ "${PV}" == *9999* ]]; then
	inherit git-r3
	# Unsure if code.illumos.org is meant to be cloned anonymously
	EGIT_REPO_URI="https://github.com/illumos/illumos-gate.git"
else
	EGIT_COMMIT="7e802e88a364973105a54b9dbcc818c9291875c1"
	SRC_URI="https://github.com/illumos/illumos-gate/archive/${EGIT_COMMIT}.tar.gz -> ${PN}-${EGIT_COMMIT}.tar.gz"
	KEYWORDS="~amd64 ~sparc"
fi

DESCRIPTION="An open-source Unix operating system"
HOMEPAGE="https://illumos.org https://code.illumos.org/plugins/gitiles/illumos-gate"
SRC_URI="${SRC_URI}
	https://www.tribblix.org/illumos-build/on-closed-bins.i386.tar.bz2
		-> illumos-on-closed-bins.i386.tar.bz2
	https://www.tribblix.org/illumos-build/on-closed-bins-nd.i386.tar.bz2
		-> illumos-on-closed-bins-nd.i386.tar.bz2
"

LICENSE="CDDL"
SLOT="0"

# Also needs java and python
BDEPEND="
	app-shells/ksh
	sys-devel/gcc:15
"

PATCHES=(
	# tribblix i386
	"${FILESDIR}/0002-allow-jdk21-builds.patch"
	"${FILESDIR}/fix-libslp-newer-java.patch"
	"${FILESDIR}/mdb-makefile.patch"
	"${FILESDIR}/mdb-packaging.patch"
	"${FILESDIR}/pkglint.patch"
	# tribblix i386-tribblix
	"${FILESDIR}/fs-local-1.patch"
	"${FILESDIR}/fs-local-2.patch"
	"${FILESDIR}/increase-maxpid.patch"
	"${FILESDIR}/libc_hwcap1.patch"
	"${FILESDIR}/undo-has-bin-file.patch"
	"${FILESDIR}/userboot-bits.patch"
)

src_unpack() {
	git-r3_src_unpack

	cd "${S}"
	unpack $A
}

src_prepare() {
	default

	# From tribblix
	sed -i 's:^SUBDIRS= py3:SUBDIRS=:' usr/src/lib/py*/Makefile || die
	rm -f usr/src/pkg/manifests/system-library-python-*-3.p5m || die
	sed -i '/$(PYTHON3_DIRS)/d' usr/src/Targetdirs || die
}

src_compile() {
	# matches SunOS rather weird `uname -p`
	case "$ARCH" in
		x86|amd64|x64-solaris) MACH="i386" ;;
		sparc|sparc64) MACH="sparc" ;;
		*) die "unsupported architecture" ;;
	esac

	# tribblix bootstrap with gentoo-prefix
	new_path="/usr/bin:/usr/sbin:/sbin:/usr/gnu/bin"
	#if test -n "${EPREFIX}"; then
	#	new_path="${new_path}:${EPREFIX}/bin"
	#fi

	# Workaround check_rtime install issue:
	# dmake: Warning: Don't know how to make target `…/usr/src/tools/proto/root_i386-nd/opt/onbld/etc/exception_lists/check_rtime'
	#mkdir -p ./usr/src/tools/proto/root_i386-nd/opt/onbld/etc/ || die
	#cp -pr ./exception_lists/ ./usr/src/tools/proto/root_i386-nd/opt/onbld/etc/ || die

	sed \
		-e "s,@MACH@,${MACH}," \
		-e "s,@CODEMGR_WS@,${S}," \
		"${FILESDIR}/illumos.sh" > illumos.sh || die

	# ksh because it needs whence(1)
	# env -i to avoid pollution from gentoo environment
	#	MAKE="/usr/bin/dmake" \
	set -- env -i \
		PATH="${new_path}" \
		LOGNAME="$(id -un)" \
		ksh ./usr/src/tools/scripts/nightly illumos.sh

	echo "$@"
	"$@" || die
}

src_install() {
	cp -pR "${S}"/proto/root_i386/* "${D}/" || die
}