#!/usr/bin/env bash

# A script to build and install the C++ library

set -eu -o pipefail

# parse arguments
# -------------------------------------------------------------------
arg() { echo "$1" | sed "s/^${2-[^=]*=}//" | sed "s/:/;/g"; }

build="Release"
prefix=""
r_build="OFF"
tiledb=""

while test $# != 0; do
  case "$1" in
  --build=*) build=$(arg "$1");;
  --prefix=*) prefix=$(arg "$1");;
  --r-build) r_build="ON";;
  --tiledb=*) tiledb=$(arg "$1");;
  esac
  shift
done

# find number of cpus
# -------------------------------------------------------------------
if [ "$(uname)" == "Darwin" ]; then
    nproc=$(sysctl -n hw.ncpu)
else
    nproc=$(nproc)
fi

# set extra cmake options
# -------------------------------------------------------------------
extra_opts=""
if [ "${build}" == "Debug" ] && [ -z "${tiledb}" ]; then
  # Debug build of TileDB from source
  extra_opts+=" -DDOWNLOAD_TILEDB_PREBUILT=OFF"
fi

if [ "$(uname -m)" == "aarch64" ]; then
  # build TileDB from source on arm
  extra_opts=+" -DDOWNLOAD_TILEDB_PREBUILT=OFF"
fi

# NOTE: set to true to debug the cmake build
if false; then
  # Debug note: this is _incredibly_ helpful in that it reveals the actual compile lines etc which
  # make itself shows by default but which cmake-driven make hides by default. Use this for any
  # non-trivial cmake debugging.
  extra_opts+=" -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON"

  # TILEDB_WERROR=OFF is necessary to build core with XCode 14; doesn't hurt for XCode 13.
  extra_opts+=" -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON -DTILEDB_WERROR=OFF -DTILEDBSOMA_ENABLE_WERROR=OFF"
  
  # Debug cmake find commands
  extra_opts+=" --debug-find"

  # Also (pro-tip), set nproc=1 to get a more deterministic ordering of output lines.
  nproc=1
fi

# set installation path
if [ -n "${prefix}"  ]; then 
  extra_opts+=" -DCMAKE_INSTALL_PREFIX=${prefix} -DOVERRIDE_INSTALL_PREFIX=OFF"
fi

# build for R only
if [ "${r_build}" == "ON" ]; then 
  extra_opts+=" -DTILEDBSOMA_BUILD_R=${r_build}"
fi

# build with custom tiledb
if [ -n "${tiledb}"  ]; then
  printf "Build with TileDB: ${tiledb}\n"
  extra_opts+=" -DFORCE_BUILD_TILEDB=OFF"
  export TileDB_DIR="${tiledb}"
  export LD_LIBRARY_PATH="${tiledb}"
  export DYLD_LIBRARY_PATH="${tiledb}"
fi

# run cmake
# -------------------------------------------------------------------
printf "Building ${build} build\n"

# cd to the top level directory of the repo
if [ "${r_build}" == "OFF" ]; then 
  cd "$(dirname "$0")/.."
fi

rm -rf build
mkdir -p build
cmake -B build -S libtiledbsoma -DCMAKE_BUILD_TYPE=${build} ${extra_opts}
cmake --build build -j ${nproc}
cmake --build build --target install-libtiledbsoma

# Skip unit test build when building for R
if [ "${r_build}" == "OFF" ]; then
  cmake --build build/libtiledbsoma --target build_tests -j ${nproc}
fi
