#!/bin/sh

# Set the number of cores
if [ -z "$PKG_NCORES" ]; then
  PKG_NCORES=$(getconf _NPROCESSORS_ONLN)
    if [ -z "$PKG_NCORES" ] || [ "$PKG_NCORES" -lt 1 ]; then
      PKG_NCORES=1
    elif [ "$PKG_NCORES" -gt 1 ]; then
      PKG_NCORES=$((PKG_NCORES / 2))
    fi
fi

# Detect OpenMP flags (prefer pkg-config for libomp)
OMP_CFLAGS=""
OMP_LIBS=""
if command -v pkg-config >/dev/null 2>&1 && pkg-config --exists libomp; then
  OMP_CFLAGS="$(pkg-config --cflags libomp)"
  OMP_LIBS="$(pkg-config --libs libomp)"
else
  # Try a small compile test to see if clang accepts -fopenmp and -lomp
  test_src="#include <omp.h>\nint main(){return 0;}"
  if echo "$test_src" | ${CC:-cc} -x c - -o /dev/null -fopenmp -lomp >/dev/null 2>&1; then
    OMP_CFLAGS="-fopenmp"
    OMP_LIBS="-lomp"
  else
    # leave empty; R's SHLIB_OPENMP_CXXFLAGS may supply flags, or build will fail
    OMP_CFLAGS=""
    OMP_LIBS=""
  fi
fi

# Substitute placeholders into Makevars
sed -e "s|@ncores@|$PKG_NCORES|g" \
    -e "s|@OMP_CFLAGS@|$OMP_CFLAGS|g" \
    -e "s|@OMP_LIBS@|$OMP_LIBS|g" \
  src/Makevars.in > src/Makevars
