#!/usr/bin/env bash
# trueref launcher — wraps the fat JAR with the JVM flags required to silence
# the FFM (foreign linker) restricted-method warning emitted by JNA-based
# tokenizer libraries and to make Lucene's Vector API path readable.
#
#   --enable-native-access=ALL-UNNAMED
#       Lucene 10 + DJL HuggingFace Tokenizers use the new java.lang.foreign
#       Linker API; on Java 21 this requires explicit native-access opt-in.
#   --add-modules jdk.incubator.vector
#       Lucene 10 ships an incubator-vector codepath that is significantly
#       faster for cosine/dot-product math but only loads if the module is
#       made readable from the unnamed module.
#
# Usage:
#   bin/trueref                              # default settings
#   bin/trueref --server.port=18080          # forward Spring properties
#   TRUEREF_JAR=/path/to/trueref.jar bin/trueref
#
# Environment overrides:
#   TRUEREF_JAR    Path to the fat JAR (default: <script-dir>/../trueref.jar)
#   JAVA          Path to the java binary (default: ${JAVA_HOME:-}/bin/java or `java` on PATH)
#   JAVA_OPTS     Extra JVM flags (e.g. -Xmx16g, -XX:+UseZGC)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
JAR_DEFAULT="${SCRIPT_DIR}/../trueref.jar"
JAR="${TRUEREF_JAR:-$JAR_DEFAULT}"

if [[ ! -f "$JAR" ]]; then
  echo "trueref: jar not found at $JAR" >&2
  echo "trueref: set TRUEREF_JAR or place trueref.jar next to this script" >&2
  exit 1
fi

if [[ -n "${JAVA:-}" ]]; then
  :
elif [[ -n "${JAVA_HOME:-}" && -x "${JAVA_HOME}/bin/java" ]]; then
  JAVA="${JAVA_HOME}/bin/java"
else
  JAVA="$(command -v java || true)"
fi

if [[ -z "${JAVA:-}" || ! -x "${JAVA}" ]]; then
  echo "trueref: java not found; set JAVA_HOME or install JDK 21+" >&2
  exit 1
fi

# ONNX Runtime CUDA EP needs cuDNN 9 on LD_LIBRARY_PATH. Many distros only ship
# cuDNN via the system package manager or via a Python wheel (nvidia-cudnn-cu12).
# If the user sets TRUEREF_CUDNN_LIB we trust it; otherwise we leave LD_LIBRARY_PATH
# alone and let CUDA fall back to CPU with a logged warning.
if [[ -n "${TRUEREF_CUDNN_LIB:-}" ]]; then
  export LD_LIBRARY_PATH="${TRUEREF_CUDNN_LIB}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
fi

exec "$JAVA" \
  --enable-native-access=ALL-UNNAMED \
  --add-modules=jdk.incubator.vector \
  ${JAVA_OPTS:-} \
  -jar "$JAR" \
  "$@"
