# Script used to generate `Makevars.win` from `Makevars.win.in`
# on Windows

###########################
# find compiler and flags #
###########################

R_EXE="${R_HOME}/bin${R_ARCH_BIN}/R"
CXX11=`"${R_EXE}" CMD config CXX11`
CXX11STD=`"${R_EXE}" CMD config CXX11STD`
CXX="${CXX11} ${CXX11STD}"
CXXFLAGS=`"${R_EXE}" CMD config CXX11FLAGS`
CPPFLAGS=`"${R_EXE}" CMD config CPPFLAGS`

# LightGBM-specific flags
LGB_CPPFLAGS=""

#########
# Eigen #
#########

LGB_CPPFLAGS="${LGB_CPPFLAGS} -DEIGEN_MPL2_ONLY -DEIGEN_DONT_PARALLELIZE"

###############
# MM_PREFETCH #
###############

ac_mm_prefetch="no"

cat > conftest.cpp <<EOL
#include <xmmintrin.h>
int main() {
  int a = 0;
  _mm_prefetch(&a, _MM_HINT_NTA);
  return 0;
}
EOL

${CXX} ${CXXFLAGS} ${CPPFLAGS} -o conftest conftest.cpp 2>/dev/null && ./conftest && ac_mm_prefetch="yes"
rm -f ./conftest
rm -f ./conftest.cpp
echo "checking whether MM_PREFETCH works...${ac_mm_prefetch}"

if test "${ac_mm_prefetch}" = "yes";
then
    LGB_CPPFLAGS="${LGB_CPPFLAGS} -DMM_PREFETCH=1"
fi

############
# MM_ALLOC #
############
ac_mm_malloc="no"

cat > conftest.cpp <<EOL
#include <mm_malloc.h>
int main() {
    char *a = (char*)_mm_malloc(8, 16);
    _mm_free(a);
    return 0;
}
EOL

${CXX} ${CXXFLAGS} ${CPPFLAGS} -o conftest conftest.cpp 2>/dev/null && ./conftest && ac_mm_malloc="yes"
rm -f ./conftest
rm -f ./conftest.cpp
echo "checking whether MM_MALLOC works...${ac_mm_malloc}"

if test "${ac_mm_malloc}" = "yes";
then
    LGB_CPPFLAGS="${LGB_CPPFLAGS} -DMM_MALLOC=1"
fi

#############
# INET_PTON #
#############

ac_inet_pton="no"

cat > conftest.cpp <<EOL
#include <ws2tcpip.h>
int main() {
  int (*fptr)(int, const char*, void*);
  fptr = &inet_pton;
  return 0;
}
EOL

${CXX} ${CXXFLAGS} ${CPPFLAGS} -o conftest conftest.cpp 2>/dev/null && ./conftest && ac_inet_pton="yes"
rm -f ./conftest
rm -f ./conftest.cpp
echo "checking whether INET_PTON works...${ac_inet_pton}"

if test "${ac_inet_pton}" = "yes";
then
    LGB_CPPFLAGS="${LGB_CPPFLAGS} -DWIN_HAS_INET_PTON=1"
fi

# Generate Makevars.win from Makevars.win.in
sed -e \
    "s/@LGB_CPPFLAGS@/$LGB_CPPFLAGS/" \
    < src/Makevars.win.in > src/Makevars.win
