# Description: WASI libc++ implementation for WebAssembly
# URL: https://libcxx.llvm.org/
# Maintainer: Danny Rawlins, crux at romster dot me
# Depends on: clang wasi-libc wasi-compiler-rt

name=wasi-libc++
version=16.0.6
_wasi_sdk_ver=20
release=1
source=(https://github.com/llvm/llvm-project/releases/download/llvmorg-$version/llvm-project-$version.src.tar.xz
	https://github.com/WebAssembly/wasi-sdk/archive/refs/tags/wasi-sdk-$_wasi_sdk_ver.tar.gz)

build() {
	cd llvm-project-$version.src

	mkdir -p build cmake/Platform
	cp "$SRC"/wasi-sdk-wasi-sdk-$_wasi_sdk_ver/wasi-sdk.cmake build
	cp "$SRC"/wasi-sdk-wasi-sdk-$_wasi_sdk_ver/cmake/Platform/WASI.cmake cmake/Platform/WASI.cmake

	cmake -G Ninja -S runtimes -B build  \
		-D CMAKE_BUILD_TYPE=Release \
		-D CMAKE_C_FLAGS_RELEASE="$CFLAGS -fno-exceptions --sysroot=/usr/share/wasi-sysroot" \
		-D CMAKE_CXX_FLAGS_RELEASE="$CXXFLAGS -fno-exceptions --sysroot=/usr/share/wasi-sysroot" \
		-D CMAKE_TOOLCHAIN_FILE=wasi-sdk.cmake \
		-D CMAKE_CXX_COMPILER_WORKS=ON \
		-D CMAKE_C_COMPILER_WORKS=ON \
		-D CMAKE_INSTALL_PREFIX=/usr/share/wasi-sysroot \
		-D LLVM_ENABLE_RUNTIMES="libcxx;libcxxabi" \
		-D LLVM_DEFAULT_TARGET_TRIPLE=wasm32-wasi \
		-D LIBCXX_ABI_VERSION=2 \
		-D LIBCXX_BUILD_EXTERNAL_THREAD_LIBRARY=OFF \
		-D LIBCXX_ENABLE_EXCEPTIONS=OFF \
		-D LIBCXX_ENABLE_EXPERIMENTAL_LIBRARY=OFF \
		-D LIBCXX_ENABLE_FILESYSTEM=OFF \
		-D LIBCXX_ENABLE_SHARED=OFF \
		-D LIBCXX_ENABLE_THREADS=OFF \
		-D LIBCXX_HAS_EXTERNAL_THREAD_API=OFF \
		-D LIBCXX_HAS_PTHREAD_API=OFF \
		-D LIBCXX_HAS_WIN32_THREAD_API=OFF \
		-D LIBCXX_INCLUDE_TESTS=OFF \
		-D LIBCXX_LIBDIR_SUFFIX=/wasm32-wasi \
		-D LIBCXXABI_BUILD_EXTERNAL_THREAD_LIBRARY=OFF \
		-D LIBCXXABI_ENABLE_EXCEPTIONS=OFF \
		-D LIBCXXABI_ENABLE_SHARED=OFF \
		-D LIBCXXABI_ENABLE_THREADS=OFF \
		-D LIBCXXABI_HAS_EXTERNAL_THREAD_API=OFF \
		-D LIBCXXABI_HAS_PTHREAD_API=OFF \
		-D LIBCXXABI_HAS_WIN32_THREAD_API=OFF \
		-D LIBCXXABI_INCLUDE_TESTS=OFF \
		-D LIBCXXABI_LIBDIR_SUFFIX=/wasm32-wasi \
		-D LIBCXXABI_SILENT_TERMINATE:BOOL=ON \
		-D UNIX=ON \
		-D WASI_SDK_PREFIX=/usr

	ninja -C build cxx cxxabi
	DESTDIR="$PKG" ninja -C build install-cxx install-cxxabi

	cd "$PKG"/usr/share/wasi-sysroot/lib/wasm32-wasi
		for f in *.a; do
		/usr/bin/llvm-ranlib $f
		/usr/bin/llvm-strip --strip-debug $f
	done
}
