#!/usr/bin/sh
#
# /usr/bin/eldric-aios — auto-selecting wrapper.
#
# Picks the CUDA variant when:
#   - eldric-aios-cuda RPM is installed (binary exists)
#   - an NVIDIA device is visible (/dev/nvidia0)
# Otherwise falls back to the CPU binary. This lets the same
# `eldric-aios.service` systemd unit (and the same /usr/bin path)
# deploy unchanged on CPU edge nodes and GPU inference nodes —
# the host's hardware picks which binary actually runs.
#
# CUDA bundled libs live under /usr/lib64/eldric-aios/cuda/ in the
# eldric-aios-cuda RPM. That directory is prepended to LD_LIBRARY_PATH
# only when we're about to exec the CUDA binary, so CPU-only hosts
# never load them.

set -eu

CUDA_BIN=/usr/libexec/eldric-aios/cuda
CPU_BIN=/usr/libexec/eldric-aios/cpu
CUDA_LIB_DIR=/usr/lib64/eldric-aios/cuda

if [ -x "${CUDA_BIN}" ] && [ -e /dev/nvidia0 ]; then
    if [ -d "${CUDA_LIB_DIR}" ]; then
        LD_LIBRARY_PATH="${CUDA_LIB_DIR}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
        export LD_LIBRARY_PATH
    fi
    exec "${CUDA_BIN}" "$@"
fi

if [ ! -x "${CPU_BIN}" ]; then
    echo "eldric-aios: no runnable binary found" \
         "(looked for ${CUDA_BIN} and ${CPU_BIN})" >&2
    exit 127
fi

exec "${CPU_BIN}" "$@"
