#!/usr/bin/env bash

# exit script if any command fails
set -e
set -o pipefail

BBDIR=$(git rev-parse --show-toplevel)

# get helpful utilities
source ${BBDIR}/scripts/utils.sh

source ${BBDIR}/env.sh
pip install -r ${BBDIR}/compiler/requirements.txt

cd ${BBDIR}/compiler
git submodule update --init

mkdir -p llvm/build && cd llvm/build
cmake -G Ninja ../llvm \
    -DLLVM_ENABLE_PROJECTS="mlir;clang" \
    -DLLVM_TARGETS_TO_BUILD="host;RISCV" \
    -DLLVM_ENABLE_ASSERTIONS=ON \
    -DCMAKE_BUILD_TYPE=RELEASE \
    -DMLIR_ENABLE_BINDINGS_PYTHON=ON \
    -DPython3_EXECUTABLE=$(which python3)
ninja #check-mlir check-clang

cd ${BBDIR}/compiler
mkdir -p build && cd build
cmake -G Ninja .. \
    -DMLIR_DIR=$PWD/../llvm/build/lib/cmake/mlir \
    -DLLVM_DIR=$PWD/../llvm/build/lib/cmake/llvm \
    -DLLVM_ENABLE_ASSERTIONS=ON \
    -DCMAKE_BUILD_TYPE=RELEASE \
    -DBUDDY_MLIR_ENABLE_PYTHON_PACKAGES=ON \
    -DPython3_EXECUTABLE=$(which python3) \
    -DPython_EXECUTABLE=$(which python3) \
    -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
ninja
#ninja check-buddy

replace_content ${BBDIR}/env.sh install-compiler "# line auto-generated by $0
export BUDDY_MLIR_BUILD_DIR=${BBDIR}/compiler/build
export LLVM_MLIR_BUILD_DIR=${BBDIR}/compiler/llvm/build
export PYTHONPATH=${BBDIR}/compiler/llvm/build/tools/mlir/python_packages/mlir_core:${BBDIR}/compiler/build/python_packages:\${PYTHONPATH}"

export BUDDY_MLIR_BUILD_DIR=${BBDIR}/compiler/build
export LLVM_MLIR_BUILD_DIR=${BBDIR}/compiler/llvm/build
export PYTHONPATH=${BBDIR}/compiler/llvm/build/tools/mlir/python_packages/mlir_core:${BBDIR}/compiler/build/python_packages:${PYTHONPATH}
