#!/usr/bin/env bash

# First, try the system's default python version
python_version=$(python3 --version 2>&1 | sed -n 's/^Python \([0-9]\+\.[0-9]\+\).*$/\1/p' )
GDB_BIN_DIR="$(dirname "$(realpath -e "${BASH_SOURCE[0]}")")"

# Make the rocgdb command with the active python version
# If the command is working exec the program to rocgdb-py_xxx binary
gdb_command="rocgdb-py_$python_version"
if [ -f "$GDB_BIN_DIR/$gdb_command" ]; then
    # Check to see if the rocgdb executable is able to run
    "$GDB_BIN_DIR/$gdb_command" --version > /dev/null 2>&1
    if [ $? == 0 ]; then
        # The binary is working in the env. exec to that
        exec "$GDB_BIN_DIR/$gdb_command" "$@"
    fi
fi
echo "Not successful in running rocgdb with active Python Version: ${python_version} in the system"
echo "Checking for working Python Version Installed"

working_gdb=""
# If the default python version didn't work,
# Make the rocgdb command with the working python version
while read -r gdb
do
    if "$gdb" --version >/dev/null 2>&1
    then
        working_gdb="$gdb"
        break
    fi
done < <(find "$GDB_BIN_DIR" -name "rocgdb-py*" | sort -r)

if [ -n "$working_gdb" ]
then
    "$working_gdb" "$@"
else
    echo "rocgdb execution Failed: No working ROCgdb Python Version found."
fi
