#!/usr/bin/env bash

set -euo pipefail

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

Runs a binary (that has been compiled with tsan) using a suppressions file.
USAGE

  exit 1
fi

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

if [ -n "${TEST_SRCDIR-}" ]; then
  # Test: bazel-out/local_linux-fastbuild/bin/doc/examples/out_of_bounds_test.runfiles/zoox/ci/runners
  # To get to the root of the workspace, we back up past `ci/runners/
  base_dir="${script_directory}/../.."
else
  # Run: bazel-out/local_linux-fastbuild/bin/ci/runners
  # We need to step into the runfiles root for the tsan target
  base_dir="${script_directory}/tsan.runfiles/zoox"
fi

# Set LMDB map size to 1GB which makes tsan happy.
export LMDB_MAP_SIZE=1073741824

tsan_suppressions_file="${base_dir}/ci/runners/tsan_suppressions.txt"
# Ensure we load our version of TSAN before the system version.
ld_preload="${base_dir}/../gcc_7_4/usr/lib/x86_64-linux-gnu/libtsan.so.0"

LD_PRELOAD=$ld_preload TSAN_OPTIONS=suppressions="$tsan_suppressions_file":second_deadlock_stack=1 "$@"
