#!/bin/sh

# Configure script for llamaR (Windows/Rtools)

# Find ggmlR lib path - try multiple methods
echo "Checking for ggmlR..."
GGMLR_LIB=""

# Method 1: Rscript with all library paths
GGMLR_LIB=$(${R_HOME}/bin/Rscript -e "cat(system.file('lib', package='ggmlR'))" 2>/dev/null)

# Method 2: Check R_LIBS and R_LIBS_USER
if [ -z "$GGMLR_LIB" ] || [ ! -d "$GGMLR_LIB" ]; then
    for libdir in $R_LIBS $R_LIBS_USER $R_LIBS_SITE; do
        # Handle path separators (semicolon on Windows)
        echo "$libdir" | tr ';' '\n' | while read -r dir; do
            if [ -f "$dir/ggmlR/lib/libggml.a" ]; then
                echo "$dir/ggmlR/lib"
                break
            fi
        done
    done | head -1 | read GGMLR_LIB 2>/dev/null || true
fi

if [ -z "$GGMLR_LIB" ] || [ ! -d "$GGMLR_LIB" ]; then
    echo "Note: ggmlR not found at configure time (will be resolved at compile time)"
else
    echo "Found ggmlR at: $GGMLR_LIB"
fi

# --- Vulkan auto-detection (for linking only, Vulkan compiled in ggmlR) ---
VULKAN_LIBS=""
if [ -n "$VULKAN_SDK" ] && [ -d "$VULKAN_SDK/Lib" ]; then
    echo "Vulkan: detected at $VULKAN_SDK (will link -lvulkan-1)"
    # Normalize the SDK path: convert Windows backslashes to forward slashes.
    # gcc/MinGW accept forward slashes, and this keeps the path safe for use in
    # the right-hand side of the sed substitution below. Native backslashes
    # (e.g. C:\VulkanSDK\1.4.350.0) would be misread by sed as backreferences
    # (\1, \4, ...) -> "invalid reference \1 on 's' command's RHS".
    VULKAN_SDK_FWD=$(printf '%s' "$VULKAN_SDK" | tr '\\' '/')
    VULKAN_LIBS="-L\"${VULKAN_SDK_FWD}/Lib\" -lvulkan-1"
else
    echo "Vulkan: not found (building without GPU support)"
fi

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

echo "Configuration complete."
