#!/bin/sh

# Get the absolute path to the directory containing this script
BASE_DIR=$(cd "$(dirname "$0")" && pwd)

wgpu_cppflags=""
wgpu_libs=""
wgpu_detected=0

for arg in "$@"; do
	case "$arg" in
        --with-wgpu)
            with_wgpu=yes
            ;;
        --without-wgpu)
            with_wgpu=no
            ;;
	esac
done

if [ -z "$with_wgpu" ]; then
    with_wgpu=auto
fi

# WebGPU detection (preferring the one in ../lib/wgpu)
if [ "$with_wgpu" != "no" ]; then
    WGPU_DIR="${BASE_DIR}/../lib/wgpu"
    WGPU_H1="${WGPU_DIR}/include/webgpu/webgpu.h"
    WGPU_H2="${WGPU_DIR}/include/webgpu/wgpu.h"
    
    # Check for shared library (Linux .so or macOS .dylib)
    wgpu_lib_path=""
    if [ -f "${WGPU_DIR}/lib/libwgpu_native.so" ]; then
        wgpu_lib_path="${WGPU_DIR}/lib/libwgpu_native.so"
    elif [ -f "${WGPU_DIR}/lib/libwgpu_native.dylib" ]; then
        wgpu_lib_path="${WGPU_DIR}/lib/libwgpu_native.dylib"
    fi

    if [ -f "$WGPU_H1" ] && [ -f "$WGPU_H2" ] && [ -n "$wgpu_lib_path" ]; then
        wgpu_cppflags="-I${WGPU_DIR}/include -DGED_USE_WGPU"
        wgpu_libs="-L${WGPU_DIR}/lib -lwgpu_native -Wl,-rpath,${WGPU_DIR}/lib"
        wgpu_detected=1
        echo "configure: wgpu-native found in $WGPU_DIR"
    else
        if [ "$with_wgpu" = "yes" ]; then
            echo "configure: error: --with-with-wgpu requested, but required files not found in ../lib/wgpu" >&2
            echo "  Looking for:" >&2
            echo "    - $WGPU_H1" >&2
            echo "    - $WGPU_H2" >&2
            echo "    - libwgpu_native.so/dylib" >&2
            exit 1
        fi
        echo "configure: wgpu-native not found or incomplete in ../lib/wgpu; falling back to CPU-only build."
        echo "  (Missing one or more of: webgpu.h, wgpu.h, or the shared library)"
    fi
fi

# Rcpp headers
RCPP_INC=`Rscript -e 'cat(system.file("include", package="Rcpp"))'`
FINAL_CPPFLAGS="$wgpu_cppflags -I\"$RCPP_INC\""
FINAL_LIBS="$wgpu_libs"

sed \
	-e "s|@GED_GPU_CPPFLAGS@|$FINAL_CPPFLAGS|g" \
	-e "s|@GED_GPU_LIBS@|$FINAL_LIBS|g" \
	"${BASE_DIR}/src/Makevars.in" > "${BASE_DIR}/src/Makevars"

exit 0
