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

EAPI=8

CMAKE_MAKEFILE_GENERATOR="ninja"
TEXMFROOT=/usr/share/texmf-dist/tex
TEXMFBIN="${TEXMFROOT}/texmf-linux-64/bin"

DESCRIPTION="ConTeXt"
HOMEPAGE="https://wiki.contextgarden.net
          https://www.pragma-ade.com
          https://github.com/contextgarden/context"

inherit cmake greadme

IUSE="doc"

COMMIT="fb28e149a3cbfdeb4224fc0ff32fa6881255b1bc"
SRC_URI="https://github.com/contextgarden/${PN}/archive/${COMMIT}.tar.gz
                        -> ${P}.tar.gz"

S="${WORKDIR}"/${PN}-${COMMIT}

LICENSE=""
SLOT="0"
KEYWORDS="~amd64"

DEPEND=""
RDEPEND="${DEPEND}
         !dev-texlive/texlive-context
         dev-texlive/texlive-fontsrecommended"
BDEPEND=""

src_prepare() {
	CMAKE_USE_DIR="${S}"/source/luametatex cmake_src_prepare
}

src_configure() {
	CMAKE_USE_DIR="${S}"/source/luametatex cmake_src_configure
}

src_compile(){
	CMAKE_USE_DIR="${S}"/source/luametatex cmake_src_compile
}

src_install(){

	DESTDIR="${T}" cmake_build install

	insinto "${TEXMFROOT}"/texmf-context

	doins -r bibtex colors context context-readme.txt fonts metapost scripts tex web2c
	
	if use doc; then
	  doins -r doc
	fi

	exeinto "${TEXMFBIN}"
	doexe ${T}/usr/bin/luametatex
	doexe scripts/context/lua/context.lua
	doexe scripts/context/lua/mtxrun.lua

	echo "PATH=${TEXMFBIN}" > "${T}"/99texmf-linux-context
	echo "OSFONTDIR=/usr/share/fonts:/usr/share/texmf-dist/tex/latex:/usr/share/texmf-dist/fonts" >> "${T}"/99texmf-linux-context
	doenvd "${T}"/99texmf-linux-context

	dosym -r "${TEXMFBIN}"/luametatex "${TEXMFBIN}"/mtxrun
	dosym -r "${TEXMFBIN}"/luametatex "${TEXMFBIN}"/context
	dosym -r "${TEXMFROOT}"/texmf-context/web2c/contextcnf.lua \
	         "${TEXMFROOT}"/texmf-context/web2c/texmfcnf.lua

	greadme_stdin <<-EOF
	You have to run 'mtxrun --generate' as normal user before first use.
	It's very likely that you also want to use the system fonts. To do it 
	define env var OSFONTDIR and run 'mtxrun --script fonts --reload'.
	You may want to install dev-texlive/texlive-fontsextra.
	Check available fonts for ConTeXt by running
	'mtxrun --script fonts --list --all'
	EOF
}

pkg_postinst() {
	greadme_pkg_postinst
}