#!/bin/bash
# Considering this script will be in cuda toolkit bin directory.
CUDA_TOOLKIT_BIN_DIR="$(dirname "$(readlink -f -- "$0")")"

setLatestNsightComputeToolDir()
{
    # Split version information <year>.<major_version>.<minor version> by "."
    IFS=. read -r  year major_version minor_version  <<< "$1"

    version_value=$(( year * 10000 + major_version * 100 + minor_version ))

    if [ $version_value -ge $latest_version ]; then
        latest_version=$version_value
        LATEST_NSIGHT_COMPUTE_TOOL_DIR=$2
    fi
}

# Pick latest Nsight Compute version if user has more than one nsight-compute-<year>.<major_version>.<minor version> or nsight-compute/<version> folder.
latest_version=0
# If installed with .deb or .rpm pkg, nsight-compute tools will be under nsight-compute/<tool_version folder> folder. e.g nsight-compute/2019.4.0
if [ -d "/opt/nvidia/nsight-compute" ]; then

    LIST_NSIGHT_COMPUTE_TOOL_DIRS=$(ls "/opt/nvidia/nsight-compute")

    while read -r nsight_compute_dir; do
        setLatestNsightComputeToolDir "$nsight_compute_dir" "/opt/nvidia/nsight-compute/$nsight_compute_dir"
    done <<< "$LIST_NSIGHT_COMPUTE_TOOL_DIRS"
fi

# If installed with .run file, nsight-compute tools will be under nsight-compute-<version> folder. e.g nsight-compute-2019.4.0
NSIGHT_COMPUTE_TOOL_DIRS=$(find "$CUDA_TOOLKIT_BIN_DIR"/.. -maxdepth 1 -name "nsight-compute-*")

while read -r nsight_compute_tool_dir_path; do
    # Split nsight compute tool dir path by "/" to get nsight compute folder name.
    nsight_compute_tool_dir_name=${nsight_compute_tool_dir_path##*/}
    # Split nsight compute tool dir name nsight-compute-<year>.<major_version>.<minor version> by "-" to get version information.
    nsight_compute_tool_version=${nsight_compute_tool_dir_name##*-}

    setLatestNsightComputeToolDir "$nsight_compute_tool_version" "$nsight_compute_tool_dir_path"

done <<< "$NSIGHT_COMPUTE_TOOL_DIRS"

if [ -z "$LATEST_NSIGHT_COMPUTE_TOOL_DIR" ]; then
    echo "ERROR : nsight-compute directory is not found under $CUDA_TOOLKIT_BIN_DIR/../ or /opt/nvidia. Nsight Compute is not installed on your system." 1>&2
    exit 1
fi

LINUX_DESKTOP_NSIGHT_COMPUTE_CLI="$LATEST_NSIGHT_COMPUTE_TOOL_DIR/target/linux-desktop-glibc_2_11_3-x64/ncu"
POWER_NSIGHT_COMPUTE_CLI="$LATEST_NSIGHT_COMPUTE_TOOL_DIR/target/linux-desktop-glibc_2_19_0-ppc64le/ncu"
LINUX_ARMSERVER_NSIGHT_COMPUTE_CLI="$LATEST_NSIGHT_COMPUTE_TOOL_DIR/target/linux-desktop-t210-a64/ncu"

ARCH=$(uname -m)

if   [ "$ARCH" = "x86_64" ]; then
    NSIGHT_COMPUTE_CLI="$LINUX_DESKTOP_NSIGHT_COMPUTE_CLI"
elif [ "$ARCH" = "ppc64le" ]; then
    NSIGHT_COMPUTE_CLI="$POWER_NSIGHT_COMPUTE_CLI"
elif [ "$ARCH" = "aarch64" ]; then
    NSIGHT_COMPUTE_CLI="$LINUX_ARMSERVER_NSIGHT_COMPUTE_CLI"
else
    echo "ERROR : Unsupported Architecture: $ARCH" 1>&2
    exit 1
fi

if [ ! -x "$NSIGHT_COMPUTE_CLI" ]; then
    echo "ERROR : $NSIGHT_COMPUTE_CLI not found." 1>&2
    exit 1
fi

exec "$NSIGHT_COMPUTE_CLI" "$@"
