#!/bin/sh
# configure — detect MPI and CUDA for dress.graph R package
# Generates src/Makevars from src/Makevars.in

PKG_CFLAGS="-I. ${SHLIB_OPENMP_CFLAGS}"
PKG_LIBS="${SHLIB_OPENMP_CFLAGS} -lm"

# Auto-detect MPI
if command -v mpicc >/dev/null 2>&1; then
    MPI_COMPILE=$(mpicc --showme:compile 2>/dev/null)
    MPI_LINK=$(mpicc --showme:link 2>/dev/null)
    if [ -n "$MPI_COMPILE" ]; then
        PKG_CFLAGS="${PKG_CFLAGS} -DDRESS_MPI ${MPI_COMPILE}"
        PKG_LIBS="${PKG_LIBS} ${MPI_LINK}"
    fi
fi

# Auto-detect CUDA: compile the CUDA kernel from source at install time
if command -v nvcc >/dev/null 2>&1 && [ -f "src/dress_cuda.cu" ]; then
    nvcc -O2 -Xcompiler -fPIC -Isrc -c src/dress_cuda.cu -o src/dress_cuda.o 2>/dev/null
    if [ -f "src/dress_cuda.o" ]; then
        PKG_CFLAGS="${PKG_CFLAGS} -DDRESS_CUDA"
        PKG_LIBS="${PKG_LIBS} dress_cuda.o -lcudart_static -ldl -lrt -lpthread"
    fi
fi

# Write Makevars
sed -e "s|@PKG_CFLAGS@|${PKG_CFLAGS}|g" \
    -e "s|@PKG_LIBS@|${PKG_LIBS}|g" \
    src/Makevars.in > src/Makevars

echo "  dress.graph configure:"
echo "    PKG_CFLAGS = ${PKG_CFLAGS}"
echo "    PKG_LIBS   = ${PKG_LIBS}"
