# We make sure that the R and Armadillo bindings are compatible (i.e., messages)
# this is why we add the R and cpp4r path
cpp4r_INCLUDE_PATH=`${R_HOME}/bin/Rscript -e "cat(system.file('include', package = 'cpp4r'))"`
INST_INCLUDE_PATH="./inst/include/armadillo4r"

# Check if cpp4r_INCLUDE_PATH is empty
if [ -z "$cpp4r_INCLUDE_PATH" ]; then
  echo "Error: cpp4r include path is empty. Please ensure the cpp4r package is installed."
  exit 1
fi

PKG_CPPFLAGS="-I${INST_INCLUDE_PATH} -I${cpp4r_INCLUDE_PATH}"

# Debugging: Print the values of the variables
echo "=================================="
echo " Compiler Configuration Variables "
echo " "
echo "cpp4r_INCLUDE_PATH: ${cpp4r_INCLUDE_PATH}"
echo "INST_INCLUDE_PATH: ${INST_INCLUDE_PATH}"
echo "PKG_CPPFLAGS: ${PKG_CPPFLAGS}"

# Check C++ standard version
echo "======================================"
echo " Checking C++ Standard Version        "
echo " "

# Create a temporary C++ file to test C++14 support
cat <<EOF> conftest_cxx14.cpp
#if __cplusplus < 201402L
#error "C++14 or newer is required"
#endif
int main() {
  return 0;
}
EOF

# Test C++14 support
if ! PKG_CPPFLAGS="${PKG_CPPFLAGS}" "${R_HOME}/bin/R" CMD SHLIB conftest_cxx14.cpp 2>/dev/null
then
  echo "Error: C++14 or newer is required to build this package."
  echo "Your current C++ compiler does not support C++14 or a newer standard."
  echo "To install armadillo4r:"
  echo " 1. Check your C++ configuration in ~/.R/Makevars to check for defined CXX flags."
  echo " 2. Update your C++ compiler."
  rm -f conftest_cxx14.cpp conftest_cxx14.o conftest_cxx14.so
  exit 1
else
  echo "C++ compiler supports C++14 or newer."
  rm -f conftest_cxx14.cpp conftest_cxx14.o conftest_cxx14.so
fi

# Create a temporary C++ file to test the compatibility with Armadillo
cat <<EOF> conftest.cpp
#include <armadillo.hpp>
using namespace arma;
int main() {
  Mat<int> A(2, 2, fill::ones);
  return 0;
}
EOF

# Test Armadillo using R CMD SHLIB
echo "==================================="
echo " Testing minimal Armadillo example "
echo " "
if ! PKG_CPPFLAGS="${PKG_CPPFLAGS}" "${R_HOME}/bin/R" CMD SHLIB conftest.cpp
then
  echo "Armadillo is not compatible with the C++ compiler used by R."
  rm -f conftest.cpp conftest.o conftest.so
  exit 1
else
  echo "Armadillo is compatible with the C++ compiler used by R."
  rm -f conftest.cpp conftest.o conftest.so
fi
