#!/bin/bash

set -Eeuo pipefail

sysroot="$(pwd)/wasix-sysroot"
tools="$(pwd)/build-host/bin"
toolchain="$(pwd)/wasix_toolchain.cmake"
# rm -rf build
mkdir -p build

cd build
#  -DCMAKE_AR="$(which llvm-ar)" -DCMAKE_RANLIB="$(which llvm-ranlib)"
cmake -S ../llvm-project/llvm -G Ninja --toolchain $toolchain -DLLVM_HOST_TRIPLE=wasm32-wasi -DLLVM_TABLEGEN=$tools/llvm-tblgen -DCLANG_TABLEGEN=$tools/clang-tblgen -DCMAKE_CROSSCOMPILING_EMULATOR=wasmer \
 -DCMAKE_BUILD_TYPE=MinSizeRel -DLLVM_TARGETS_TO_BUILD=WebAssembly -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=SPIRV -DLLVM_ENABLE_PROJECTS="clang;lld" -DLLVM_EXTERNAL_CLSPV_SOURCE_DIR="$(pwd)/../clspv" -DLLVM_BUILD_TOOLS=OFF -DLLVM_BUILD_TESTS=OFF -DLLVM_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_UTILS=OFF -DLLVM_INCLUDE_EXAMPLES=OFF -DLLVM_ENABLE_BINDINGS=OFF -DLLVM_INCLUDE_BENCHMARKS=OFF -DLLVM_BUILD_DOCS=OFF -DLLVM_ENABLE_OCAMLDOC=OFF -DLLVM_ENABLE_BACKTRACES=OFF -DLLVM_ENABLE_UNWIND_TABLES=OFF -DLLVM_ENABLE_CRASH_OVERRIDES=OFF -DLLVM_ENABLE_LIBXML2=OFF -DLLVM_ENABLE_LIBEDIT=OFF -DLLVM_ENABLE_LIBPFM=OFF -DLLVM_BUILD_STATIC=ON -DCMAKE_SKIP_RPATH=ON -DCMAKE_SKIP_INSTALL_RPATH=ON -DNO_INSTALL_RPATH=ON -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DLLVM_ENABLE_PIC=OFF -DLLVM_ENABLE_ZLIB=OFF -DCLANG_ENABLE_ARCMT=OFF -DCLANG_ENABLE_STATIC_ANALYZER=OFF -DCLANG_BUILD_TOOLS=OFF -DLLVM_ENABLE_RUNTIMES="" -DLLVM_ENABLE_LIBCXX=ON -DLLVM_TOOL_LLVM_DRIVER_BUILD=ON -DLLVM_ENABLE_LTO=OFF -DHAVE_SETRLIMIT=NO -DCLANG_HAVE_RLIMITS=NO -DBUILD_SHARED_LIBS=OFF -DLLVM_BUILD_LLVM_DYLIB=OFF -DLLVM_EXTERNAL_PROJECTS=clspv
ninja bin/llvm tools/clang/lib/Headers/all

# TODO: investigate LLVM_DRIVER_TOOLS