cd src

unset https_proxy

set -e

# https://github.com/Macaulay2/homebrew-tap/blob/main/Formula/macaulay2.rb#L69
# Place the submodules, since the tarfile doesn't include them
git clone https://github.com/Macaulay2/M2-emacs.git M2/Macaulay2/editors/emacs
git clone https://github.com/Macaulay2/memtailor.git M2/submodules/memtailor
git clone https://github.com/Macaulay2/mathic.git M2/submodules/mathic
git clone https://github.com/Macaulay2/mathicgb.git M2/submodules/mathicgb

BUILD_OPTIONS=$SAGE_MACAULAY2_BUILD_OPTIONS

export Eigen3_DIR=$SAGE_LOCAL
export Flint_DIR=$SAGE_LOCAL
export Factory_DIR=$SAGE_LOCAL

# https://github.com/Macaulay2/M2/wiki/Building-M2-from-source-using-CMake
# -DWITH_OMP=OFF makes OpenMP optional.
cd M2/BUILD/build
sdh_cmake -GNinja -S../.. -B. \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_PREFIX_PATH="$SAGE_LOCAL" \
      -DCMAKE_BUILD_RPATH="${SAGE_LOCAL}/lib" \
      -DCMAKE_INSTALL_RPATH="${SAGE_LOCAL}/lib" \
      -DWITH_OMP=OFF \
      $BUILD_OPTIONS
if [ -n "$SAGE_MACAULAY2_TARGETS" ]; then
   # "Note that this target must be built separately, before proceeding to M2-binary."
   cmake --build . --target $SAGE_MACAULAY2_TARGETS
fi
cmake --build . --target M2-core M2-emacs
cmake --install .
