#!/usr/bin/env sh

# Set TMPDIR to avoid creating temp directories in /tmp for CRAN compliance
export TMPDIR="${PWD}/src/libK/build_tmp"
mkdir -p "${TMPDIR}"

. tools/cmake_config.sh
if test -z "${CMAKE_BIN}"; then
   ## also error to end configure here
   as_fn_error $? "Could not find 'cmake'." "$LINENO" 5
fi
export PATH=$PATH:$(cd $(dirname -- $CMAKE_BIN) && pwd -P)

tools/r_config.sh

# It is required that setup.sh is run before R CMD build rlibkriging when submit to CRAN. 
if [ ! -d R ]; then
  echo "R directory does not exist, running setup.sh"
  tools/setup.sh
else
  echo "R directory exists, skipping setup.sh"
fi

tools/build.sh

# Clean up temporary directory used for CMake
rm -rf "${TMPDIR}"

# Also clean up any CMake temp directories that were created in /tmp during this build
# Find temp directories created in the last 10 minutes
find /tmp -maxdepth 1 -name "tmp.*" -type d -user $(id -u) -mmin -10 2>/dev/null | while read dir; do
  # Only remove if it contains CMake files (to be safe)
  if [ -f "$dir/CMakeCache.txt" ] || [ -d "$dir/CMakeFiles" ]; then
    rm -rf "$dir" 2>/dev/null || true
  fi
done
