#!/bin/bash
#
# This is a helper script to test if the TMM for a given chum is less than a
# threshold. It exits with 0 if the mean distance error is below the given
# threshold, 1 if it is above the threshold, and 125 if it fails to calculate
# the metric.
#
# Example usage:
#   bash test_tmm --tmm_threshold=5 --chum_uri=<uri>

# Enable unofficial bash strict mode.
set -euo pipefail

usage()
{
  echo "Example usage: ./test_tmm --tmm_threshold=5 --chum_uri=<uri>"
}

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

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

tmp_dir=$(mktemp -d)
output_basename="$tmp_dir/output"
output_summary_file="${output_basename}_summary.txt"

readonly tmm_threshold chum_uri tmp_dir output_basename output_summary_file

bazel run //sim/agent_metrics:run_metrics -- --chum_uri="$chum_uri" \
    --output_basename="$output_basename" || exit 125

# Parse the first line of the output file which looks like:
#    Mean distance error: 0.511411
mean_dist_error=$(cat $output_summary_file | sed -n -e 's/^.*Mean distance error: //p')
readonly mean_dist_error

if [[ mean_dist_error == "" ]]; then
  exit 125
fi

if [[ $(echo "$mean_dist_error > $tmm_threshold" | bc -l) == "1" ]]; then
  echo "Mean dist error: $mean_dist_error > $tmm_threshold"
  exit 1
fi

echo "Mean dist error: $mean_dist_error <= $tmm_threshold"
exit 0
