#!/bin/sh
# 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 "."
    year=$(echo "$1" | cut -d'.' -f1)
    major_version=$(echo "$1" | cut -d'.' -f2)
    minor_version=$(echo "$1" | cut -d'.' -f3)

    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
    for nsight_compute_dir in /opt/nvidia/nsight-compute/*; do
        if [ ! -e "$nsight_compute_dir" ]; then
            # Glob didn't match anything. Let's skip this single iteration.
            continue
        fi
        setLatestNsightComputeToolDir "$(basename "$nsight_compute_dir")" "$nsight_compute_dir"
    done
fi

# If installed with .run file, nsight-compute tools will be under nsight-compute-<version> folder. e.g nsight-compute-2019.4.0
for nsight_compute_tool_dir_path in "$CUDA_TOOLKIT_BIN_DIR"/../nsight-compute-*; do
    if [ ! -e "$nsight_compute_tool_dir_path" ]; then
        # Glob didn't match anything. Let's skip this single iteration.
        continue
    fi
    # 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

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

# Run the script shipped with NCU to launch the correct version of the tool instead of selection at runtime
if [ -x "$LATEST_NSIGHT_COMPUTE_TOOL_DIR/ncu" ]; then
    NSIGHT_COMPUTE_CLI="$LATEST_NSIGHT_COMPUTE_TOOL_DIR/ncu"
fi

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

exec "$NSIGHT_COMPUTE_CLI" "$@"
