#!/usr/bin/env bash

# Template for cuda memcheck tools.

set -euo pipefail

# Template variable replaced by expand_template.
memcheck_tool="{{CUDA_MEMCHECK_TOOL}}"

if [ $# == 0 ] || [ "$1" == '--help' ] || [ "$1" == '-h' ]; then
  cat <<USAGE
Usage: $0 your-program [your-program-options]

Runs cuda memcheck with the "$memcheck_tool" tool on the given program.
USAGE

  exit 1
fi

# NOTE: script_directory is going to look different in run/test.
script_directory="$(dirname "${BASH_SOURCE[0]}")"

base_dir="${script_directory}/../.."

if ! [[ -x "$base_dir"/../cuda_repo/cuda/bin/cuda-memcheck ]]; then
  base_dir="$script_directory"/cuda_"$memcheck_tool".runfiles/zoox
  if ! [[ -x "$base_dir"/../cuda_repo/cuda/bin/cuda-memcheck ]]; then
    >&2 echo "Failed to find cuda_memcheck runfiles!"
    exit 1
  fi
fi

if ! [[ -e /dev/nvidia-uvm-tools ]]; then
  >&2 echo "/dev/nvidia-uvm-tools not found! cuda-memcheck may not work properly."
fi

# Just an arbitrary value to get it to exit with non-zero if the Valgrind
# checks fail but the tests succeed.
error_exit_code=6

"$base_dir"/../cuda_repo/cuda/bin/cuda-memcheck \
  --leak-check full \
  --racecheck-report all \
  --tool "$memcheck_tool" \
  --error-exitcode "$error_exit_code" \
  "$@"
