#!/bin/bash
#
# Given two Git SHAs, this script performs a git bisect between them based on
# a mean distance error threshold (tmm_threshold). Old (good) behavior is
# considered to be below the threshold and new (bad) behavior is above the
# threshold.
#
# Note: If bisect does not exit cleanly, try the following to get back to a
#       clean state:
#           git reset --hard && git clean -f -d && git bisect reset
#
# Example usage:
#   bash bisect_tmm --tmm_threshold=5 --chum_uri=<uri> --start_sha=<sha> --end_sha<sha>

# Enable unofficial bash strict mode.
set -euo pipefail

usage()
{
  echo "Example usage: ./bisect_tmm --tmm_threshold=5 --chum_uri=<uri> \
        --start_sha=<sha> --end_sha<sha>"
}

while [[ $# -gt 0 ]]
do
  case $1 in
    --tmm_threshold=*)
      threshold="${1#*=}"
      shift 1
      ;;
    --chum_uri=*)
      chum_uri="${1#*=}"
      shift 1
      ;;
    --start_sha=*)
      start_sha="${1#*=}"
      shift 1
      ;;
    --end_sha=*)
      end_sha="${1#*=}"
      shift 1
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      echo "Unrecognized argument: ${1}"
      usage
      exit 1
      ;;
  esac
done

if [[ -z "${tmm_threshold+x}" || -z "${chum_uri+x}"  || -z "${start_sha+x}"  \
      || -z "${end_sha+x}" ]]; then
  echo "Incorrect number of arguments."
  usage
  exit 1
fi

tmp_dir=$(mktemp -d)
readonly tmp_dir

# Copy the script which tests the tmm to a temporary folder so that it is
# available during the bisect.
cp ./sim/agent_metrics/scripts/test_tmm.sh "$tmp_dir"
chmod +x "$tmp_dir/test_tmm.sh"

git bisect start $end_sha $start_sha
git bisect run "$tmp_dir/test_tmm.sh" "--tmm_threshold=$tmm_threshold" "--chum_uri=$chum_uri"
