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

EAPI=9

inherit elisp-common

DESCRIPTION="GNU Forth is a fast and portable implementation of the ANSI Forth language"
HOMEPAGE="https://www.gnu.org/software/gforth"
SRC_URI="https://net2o.de/gforth-dist/Snapshots/${PV}/${P}.tar.xz"

LICENSE="GPL-3"
SLOT="0"
KEYWORDS="~amd64 ~arm ~arm64 ~ppc ~riscv ~x86 ~x64-macos"
IUSE="+check emacs"

DEPEND="dev-libs/ffcall
	dev-libs/libltdl
	dev-libs/wayland
	media-libs/freetype
	media-libs/harfbuzz:=
	media-libs/libglvnd
	media-libs/libpulse
	media-libs/libwebp:=
	media-libs/opus
	sci-geosciences/gpsd:=
	sys-apps/texinfo
	sys-libs/binutils-libs:=
	virtual/zlib:=
	x11-libs/libX11
	x11-libs/libXext
	x11-libs/libxkbcommon
	x11-libs/libXrandr
	emacs? ( >=app-editors/emacs-23.1:* )"

RDEPEND="${DEPEND}"

SITEFILE="50${PN}-gentoo.el"

MAKEOPTS+=" -j1"

PATCHES=(
	"${FILESDIR}"/${PN}-1.0.2-fix-libs.patch
	"${FILESDIR}"/${PN}-1.0.2-trygcc.patch
	)

src_prepare() {
	default

	# including <bfd.h> requires a more modern ansidecl.h than provided
	cp /usr/include/ansidecl.h engine

	# does not work if $KERNEL is defined outside of the script
	sed -i -e "s/KERNEL/GKERNEL/g" libforth.in || die

	# drop automatic installation of *.el files but keep them
	# for elisp-... commands
	sed -i -e "s/install-man install-elc/install-man/" Makefile.in || die
	sed -i -e "s/gforth.fi.install start-gforth.el/gforth.fi.install/" \
		Makefile.in || die
	if ! use emacs; then
		# do not try to generate start-gforth.el file - requires emacs
		sed -i -e "s/doc start-gforth.el ch/doc ch/" Makefile.in || die
		sed -i -e "s/.fi start-gforth.el @b/.fi @b/" Makefile.in || die
	fi

	# do not rebuild already provided documentation
	sed -i -e "s/^doc:/doc: # /" Makefile.in || die
	# above change triggers rebuild of prim.b and kernel/aliases.fs
	# so drop dependency on Makefile.in
	sed -i -e "s/0.vmg Makefile.in pre/0.vmg pre/" Makefile.in || die
}

src_configure() {
	econf \
		$(use emacs || echo "--without-lispdir") \
		$(use_with check)
}

src_compile() {
	VERBOSE=1 emake
}

src_install() {
	VERBOSE=1 emake DESTDIR="${D}" install
	VERBOSE=1 einstalldocs

	# drop static libraries files and not needed *.la files
	# be aware that *.la files in /usr/lib64/gforth are needed
	# for dynamic laoding of precompiled FORTH-code at runtime
	find "${ED}" -type f -name '*.a' -delete || die
	find "${ED}" -type f -name 'libgforth*.la' -delete || die

	dodoc NEWS* ToDo doc/glossaries.doc doc/*.pdf

	if use emacs; then
		elisp-install ${PN} gforth.el gforth.elc
		mv start-gforth.el ${SITEFILE}
		elisp-site-file-install ${SITEFILE}
	fi
}

pkg_postinst() {
	use emacs && elisp-site-regen
}

pkg_postrm() {
	use emacs && elisp-site-regen
}