#!/usr/bin/env bash

set -euo pipefail

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

Runs valgrind on the given program using Zoox's settings and suppressions file.
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"/../valgrind_repo/bin/valgrind ]]; then
  base_dir="$script_directory"/valgrind.runfiles/zoox
  if ! [[ -x "$base_dir"/../valgrind_repo/bin/valgrind ]]; then
    echo Failed to find valgrind runfiles!
    exit 1
  fi
fi

suppressions_file="${base_dir}/ci/runners/valgrind_suppressions.txt"
# 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

# Set LMDB map size to 1GB which valgrind is happy with.
export LMDB_MAP_SIZE=1073741824

export VALGRIND_LIB="$base_dir"/../valgrind_repo/lib/valgrind

# Passing extra_valgrind_args last so that it can override any other arguments
# passed in here.
"$base_dir"/../valgrind_repo/bin/valgrind \
  --suppressions="$suppressions_file" \
  --gen-suppressions=all \
  --error-exitcode="$error_exit_code" \
  --max-stackframe=2500000 \
  ${EXTRA_VALGRIND_ARGS:-} \
  "$@"
