#!/usr/bin/env bash

# Check the cuda-gdb executables in order of preference
# for unresolved shared library references.

# Start with the value of CUDA_GDB_BINARIES, so that end-users can put their own
# at the front of the list.
CUDA_GDB_BINARIES="$CUDA_GDB_BINARIES cuda-gdb-python3.12-tui"
CUDA_GDB_BINARIES="$CUDA_GDB_BINARIES cuda-gdb-python3.11-tui"
CUDA_GDB_BINARIES="$CUDA_GDB_BINARIES cuda-gdb-python3.10-tui"
CUDA_GDB_BINARIES="$CUDA_GDB_BINARIES cuda-gdb-python3.9-tui"
CUDA_GDB_BINARIES="$CUDA_GDB_BINARIES cuda-gdb-python3.8-tui"
CUDA_GDB_BINARIES="$CUDA_GDB_BINARIES cuda-gdb-minimal"

# We depend on this for detecting ldd not finding
# all the required shared libraries
set -o pipefail

# Check if a binary's shared library requirements are met
# by the system this script is running on, and if so
# exec it with the passed-in command line args.
# In such cases this function does not return.
exec_cuda_gdb_binary()
{
    binary="$1"
    ldd "$binary" 2>&1 | grep -q 'not found' 2>&1 > /dev/null
    if [ $? -ne 0 ]; then
        shift
        if [ "$1" == "--version" ]; then
            echo "exec:" "$binary" "$@"
        fi
        exec "$binary" "$@"
    fi
}

# Check $PATH first
for binary in $CUDA_GDB_BINARIES; do
    BINARY=`which "$binary" 2> /dev/null`
    if [ "$BINARY" != "" -a -f "$BINARY" ]; then
        exec_cuda_gdb_binary "$BINARY" "$@"
    fi
done

# No binary could be found on $PATH
# Check again alongside this wrapper script.
# Note that 'dirname cuda-gdb-python3.12-tui' will return '.'
# even without an explicit leading './'
WRAPPER_SCRIPT_DIR=`dirname $0`
for binary in $CUDA_GDB_BINARIES; do
    if [ -f "$WRAPPER_SCRIPT_DIR/$binary" ]; then
        exec_cuda_gdb_binary "$WRAPPER_SCRIPT_DIR/$binary" "$@"
    fi
done

echo "Could not find system compatible cuda-gdb binary executable" 1>&2
echo "Supported binaries are:" $CUDA_GDB_BINARIES 1>&2
exit 1
