#!/bin/sh

# Configure script for llamaR package

# Check that ggmlR is installed (warning only, actual check at compile time)
echo "Checking for ggmlR..."
GGMLR_LIB=$(${R_HOME}/bin/Rscript -e "cat(system.file('lib', package='ggmlR'))" 2>/dev/null)
if [ -z "$GGMLR_LIB" ] || [ ! -d "$GGMLR_LIB" ]; then
    echo "Note: ggmlR not found (will be checked at compile time)"
else
    if [ ! -f "$GGMLR_LIB/libggml.a" ]; then
        echo "Note: libggml.a not found in ggmlR (will be checked at compile time)"
    else
        echo "Found ggmlR at: $GGMLR_LIB"
    fi
fi

# --- Vulkan auto-detection (for linking only, Vulkan compiled in ggmlR) ---
VULKAN_LIBS=""
if pkg-config --exists vulkan 2>/dev/null; then
    echo "Vulkan: detected (will link -lvulkan)"
    VULKAN_LIBS="$(pkg-config --libs vulkan)"
else
    echo "Vulkan: not found (building without GPU support)"
fi

# Get OpenMP flags from R
OPENMP_CXXFLAGS=""
MAKECONF=$(${R_HOME}/bin/Rscript -e "cat(R.home('etc'))" 2>/dev/null)/Makeconf
if [ -f "$MAKECONF" ]; then
    OPENMP_CXXFLAGS=$(grep "^SHLIB_OPENMP_CXXFLAGS" "$MAKECONF" | sed 's/.*= *//')
fi

# Generate Makevars from template
sed -e "s|@OPENMP_CXXFLAGS@|${OPENMP_CXXFLAGS}|g" \
    -e "s|@VULKAN_LIBS@|${VULKAN_LIBS}|g" \
    src/Makevars.in > src/Makevars

echo "Configuration complete."
