#!/usr/bin/env bash

set -euo pipefail

if [ $# == 0 ] || [ "$1" == '--help' ] || [ "$1" == '-h' ]; then
  cat <<USAGE
Usage: $0 your-program [your-program-options]
Runs cuda code coverage on the given program.
Coverage results are written to bazel-out/_coverage/_coverage_report_cuda.dat.
User can concatenate the cpu coverage dat with the gpu coverage dat to generate
the full report.
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/nvdisasm ]]; then
  >&2 echo "Failed to find nvdisasm runfiles!"
  exit 1
fi

# Adds nvdisasm to PATH.
export PATH=$PATH:"$base_dir"/../cuda_repo/cuda/bin/

# Load ubuntu 16.04 libstdc++ to fix missing symbol issue. Detailed discussion:
# https://github.com/NVlabs/NVBit/issues/3
LD_PRELOAD="/usr/lib/x86_64-linux-gnu/libstdc++.so.6 ../nvbit_code_cov/libstdc++.so.6.0.21 ../nvbit_code_cov/instr_count.so" "$@"
