# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Contributor: omni <omni+alpine@hack.org>
# Maintainer: Celeste <cielesti@protonmail.com>
maintainer="Celeste <cielesti@protonmail.com>"
pkgname=dune
pkgver=3.19.0
pkgrel=0
pkgdesc="A composable build system for OCaml (formerly Jbuilder)"
url="https://dune.build/"
arch="all"
license="MIT"
checkdepends="bash"
makedepends="ocaml"
provides="jbuilder=$pkgver-r$pkgrel"
subpackages="$pkgname-doc $pkgname-emacs::noarch"
source="$pkgname-$pkgver.tar.gz::https://github.com/ocaml/dune/archive/$pkgver.tar.gz"
options="!check"  # FIXME requires ocaml-menhir

# When enabling dune-configurator for riscv64,
# create an OCaml 5 variant of ocaml4-abuild-find.
_configurator="dune-configurator"

case "$CARCH" in
	arm*|x86) options="$options textrels" ;;
	riscv64|loongarch64)
		_configurator=""
		makedepends="${makedepends//ocaml/ocaml5}"
		;;
esac

subpackages="$subpackages $_configurator"

prepare() {
	default_prepare

	# This allows 'dune --version' to output the correct version instead of "n/a"
	sed -i "/^(name dune)/a (version $pkgver)" dune-project
	# This enables dune-configurator to use the vendored csexp module
	sed -i 's/stdune.csexp/dune-configurator.csexp/' vendor/csexp/src/dune
}

build() {
	./configure --libdir="$(ocamlc -where)" \
		--bindir="/usr/bin" --sbindir="/usr/sbin" --etcdir="/etc" \
		--mandir="/usr/share/man" --docdir="/usr/share/doc" \
		--datadir="/usr/share"

	ocaml boot/bootstrap.ml --verbose
	./dune.exe build \
		-p dune,dune-configurator \
		--profile dune-bootstrap --verbose
}

check() {
	./dune.exe runtest --verbose
}

package() {
	./dune.exe install \
		--destdir="$pkgdir" \
		dune $_configurator

	# Duplicate of usr/share/doc/dune
	rm -Rf "$pkgdir"/usr/share/doc/dune-configurator
}

emacs() {
	depends="$pkgname"
	install_if="$pkgname=$pkgver-r$pkgrel emacs"
	pkgdesc="Emacs plugins for $pkgname"

	amove usr/share/emacs
}

configurator() {
	pkgdesc="System config helper for the Dune OCaml build system"
	provides="$subpkgname-dev=$pkgver-r$pkgrel"

	amove usr/lib/ocaml/"$subpkgname"
}

prepare_py_provides() {
	local datadir="${subpkgdir:-$pkgdir}"
	local pkgbasedir=${pkgbasedir:-"$startdir/pkg"}
	local controldir="$pkgbasedir"/.control.${subpkgname:-$pkgname}

	makedepends_has "ocaml5" && return 0
	options_has "!tracedeps" && return 0

	ocaml4-abuild-find provides \
		"$datadir"/usr/lib/ocaml \
		"$controldir" \
		"$pkgver-r$pkgrel"
}

scan_python3_dependency() {
	local controldir="$2" datadir="$3"

	makedepends_has "ocaml5" && return 0

	ocaml4-abuild-find requires \
		"$datadir"/usr/lib/ocaml \
		"$controldir"
}

sha512sums="
0d3210ecf34a6ed4a43fe76697067ef756902d444159f1ea676d228651d063290fb2a22f3077dfdf66dbf6b345ee68f0ad41f27cb62facdbca2672f75c989b03  dune-3.19.0.tar.gz
"
