# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=binaryen
pkgver=123
pkgrel=0
pkgdesc="Compiler infrastructure and toolchain library for WebAssembly, in C++"
url="https://github.com/WebAssembly/binaryen"
arch="all !s390x"
license="Apache-2.0"
makedepends="
	clang
	cmake
	python3
	samurai
	"
checkdepends="
	filecheck
	gtest-dev
	llvm-test-utils
	nodejs
	"
subpackages="$pkgname-dev"
# test/spec/testsuite submodule
_testsuite_gitrev=e05365077e13a1d86ffe77acfb1a835b7aa78422
source="https://github.com/WebAssembly/binaryen/archive/version_$pkgver/binaryen-$pkgver.tar.gz
	https://github.com/WebAssembly/testsuite/archive/$_testsuite_gitrev/binaryen-testsuite-$_testsuite_gitrev.tar.gz
	use-system-gtest.patch
	"
builddir="$srcdir/$pkgname-version_$pkgver"

prepare() {
	rmdir test/spec/testsuite
	mv "$srcdir"/testsuite-$_testsuite_gitrev test/spec/testsuite

	# Requires v8 command.
	rm -r test/lit/d8

	default_prepare
}

build() {
	case "$CARCH" in
	arm*|aarch64|riscv64|loongarch64)
		export CFLAGS="${CFLAGS/-fstack-clash-protection}"
		export CXXFLAGS="${CFLAGS/-fstack-clash-protection}"
		;;
	esac

	CC=clang \
	CXX=clang++ \
	LDFLAGS="$LDFLAGS -Wl,-z,stack-size=0x100000" \
	cmake -G Ninja -B build \
		-DCMAKE_BUILD_TYPE=Release \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DCMAKE_INSTALL_LIBDIR=lib \
		-DCMAKE_VERBOSE_MAKEFILE=ON \
		-DBUILD_SHARED_LIBS=ON \
		-DBUILD_TESTS=$(want_check && echo ON || echo OFF)
	cmake --build build
}

check() {
	# Tests are extremely chatty.
	msg 'running tests with stdout/stderr redirected into ./check.log...'
	python3 check.py --binaryen-bin build/bin > check.log 2>&1 || {
		echo 'tests failed, printing last 1000 lines of check.log:' >&2
		tail -n 1000 check.log

		case "$CARCH" in
			# XXX: Ignore test failures on 32-bit arches (broken tests),
			#  ppc64le and riscv64.
			arm* | ppc64le | riscv64 | x86) return 0;;
			*) return 1;;
		esac
	}
}

package() {
	DESTDIR="$pkgdir" cmake --install build
}

dev() {
	default_dev

	# XXX: doesn't exist on riscv64
	amove usr/bin/binaryen-unittests || true
}

sha512sums="
efb94fc8e0fa67d1d82d0b3c86b3a6e8f82cc4e8d403a8e1ef627399c8b30f8c071927943265fdec9ce71dbfa487087bd8ebe80b93f56e0cf813acb7ab311839  binaryen-123.tar.gz
5bd5ea065eb2680906db3f6d34a4ae39a4458ef2bda0dd8551ab465477aa998a9254c51de807b26902dbc165ed628c663b6e0a150c6d421b5f14f1da2599e746  binaryen-testsuite-e05365077e13a1d86ffe77acfb1a835b7aa78422.tar.gz
079fb04e452dc72ec4eb9edbb1f2375c52a1f8801f1de0ac4afd7d99f19882329150ee5d986d6f52bec3dc1a1217ed1912ccd16085b8777b8b2ae37ec771e941  use-system-gtest.patch
"
