#!/bin/sh

echo "Configure nativeORT..."

ORT_FOUND=0

# try pkg-config
if pkg-config --exists onnxruntime 2>/dev/null; then
  ORT_CFLAGS=$(pkg-config --cflags onnxruntime)
  ORT_LIBS=$(pkg-config --libs onnxruntime)
  ORT_FOUND=1
  echo "  Found ORT via pkg-config"

# try environment variable (not recommended, but avaialable)
elif [ -n "$ORT_ROOT" ]; then
  ORT_CFLAGS="-I${ORT_ROOT}/include"
  ORT_LIBS="-L${ORT_ROOT}/lib -lonnxruntime -Wl,-rpath,${ORT_ROOT}/lib"
  ORT_FOUND=1
  echo "  Found ORT via ORT_ROOT: $ORT_ROOT"

# try user cache
else
  ORT_DATA=$(Rscript --vanilla -e \
    "cat(tools::R_user_dir('nativeORT', which='data'))" \
    2>/dev/null)

  # handle multi-platform options
  if [ -n "$ORT_DATA" ]; then
    if [ -f "${ORT_DATA}/lib/libonnxruntime.dylib" ] || \
       [ -f "${ORT_DATA}/lib/libonnxruntime.so" ] || \
       [ -f "${ORT_DATA}/lib/onnxruntime.dll" ]; then
      ORT_CFLAGS="-I\"${ORT_DATA}/include\""
      ORT_LIBS="-L\"${ORT_DATA}/lib\" -lonnxruntime -Wl,-rpath,\"${ORT_DATA}/lib\""
      ORT_FOUND=1
      echo "  Found ORT in user cache: $ORT_DATA"
    fi
  fi
fi


# if not found, build w/o install - user must use nativeORT::ort_install() first
if [ "$ORT_FOUND" -eq 0 ]; then
  echo "  ORT not found - building stub."
  echo "  Run ort_install() after installation to enable inference."
  ORT_CFLAGS=""
  ORT_LIBS=""
fi


# --- now the Makevars
if [ "$ORT_FOUND" -eq 1 ]; then
  sed \
    -e "s|@ORT_CFLAGS@|${ORT_CFLAGS} -DHAVE_ORT|" \
    -e "s|@ORT_LIBS@|${ORT_LIBS}|" \
    src/Makevars.in > src/Makevars
else
  sed \
    -e "s|@ORT_CFLAGS@||" \
    -e "s|@ORT_LIBS@||" \
    src/Makevars.in > src/Makevars
fi

echo "Configuration complete."
