#!/bin/sh

LLVM_SOURCE_DIR=$Y_WORKSPACE_ROOT/userspace/target/ports/meta-llvm/source/llvm-project-${Y_PORT_VERSION}.src
CMAKE_TOOLCHAIN=$Y_PORT_UTILS/toolchain-${Y_ARCH}.cmake

set -e

build_dir=$3

case $Y_ARCH in
    x86_64)
        LLVM_TARGET_NAME=X86
        ;;
    aarch64)
        LLVM_TARGET_NAME=AArch64
        ;;
    riscv64)
        LLVM_TARGET_NAME=RISCV
        ;;
    **)
        echo "Unsupported LLVM Yggdrasil target: $Y_ARCH" >&2
        exit 1
        ;;
esac

mkdir -p $build_dir
cd $build_dir
if [ ! -f build.ninja ]; then
    cmake \
        --toolchain=$CMAKE_TOOLCHAIN \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_SYSROOT=$Y_SYSROOT \
        -DCMAKE_INSTALL_PREFIX=$Y_SYSROOT \
        -DLLVM_HOST_TRIPLE=$Y_TRIPLE \
        -DLLVM_TARGETS_TO_BUILD=$LLVM_TARGET_NAME \
        -DLLVM_ENABLE_PROJECTS="lld;clang" \
        -DLLVM_INCLUDE_BENCHMARKS=OFF \
        -DLLVM_INCLUDE_EXAMPLES=OFF \
        -DLLVM_INCLUDE_TESTS=OFF \
        -DLLVM_INCLUDE_TOOLS=ON \
        -DLLVM_ENABLE_THREADS=OFF \
        -DLLVM_ENABLE_RTTI=OFF \
        -DLLVM_ENABLE_ASSERTIONS=ON \
        -DLLVM_ENABLE_LIBXML2=OFF \
        -DLLVM_CCACHE_BUILD=ON \
        -DLLVM_BUILD_TESTS=OFF \
        -DLLVM_BUILD_EXAMPLES=OFF \
        -DLLVM_BUILD_BENCHMARKS=OFF \
        -DLLVM_BUILD_DOCS=OFF \
        -DLLVM_USE_LINKER=lld \
        -GNinja \
        $LLVM_SOURCE_DIR/llvm
fi

cmake --build . -j
