#!/usr/bin/env bash

set -euo pipefail

WORKSPACE="$(bazel info workspace)"
CHUM_URI=""
CHUM_OUTPUT_ROOT=""
CHUM_OUTPUT_VARIANT=""

for opt in "$@"; do
  case $opt in
    --output_chum_root=*)
      CHUM_OUTPUT_ROOT=${opt#*=}
    ;;
    --output_chum_variant=*)
      CHUM_OUTPUT_VARIANT=${opt#*=}
    ;;
    --uri=*)
      CHUM_URI=${opt#*=}
    ;;
    *) echo "Invalid option $opt" >&2
    ;;
  esac
done

if [ -z "$CHUM_URI" ]
then
  echo "--uri is missing, must provide chum uri." >&2
  exit 1
fi

if [ -z "$CHUM_OUTPUT_ROOT" ]
then
  echo "--output_chum_root is missing." >&2
  exit 1
fi

if [ -z "$CHUM_OUTPUT_VARIANT" ]
then
  echo "--output_chum_variant is missing." >&2
  exit 1
fi


if [[ ! $CHUM_URI == chum://* ]] ;
then
  CHUM_URI="chum://"$CHUM_URI
fi

echo "Run command"
echo "bazel run //sim/log_test_generator:create_log_test -- --scenario_dir $WORKSPACE/log_tests/scenarios/  $CHUM_URI"
scenarios_filename=$(bazel run //sim/log_test_generator:create_log_test -- --scenario_dir $WORKSPACE/log_tests/scenarios/ $CHUM_URI | grep "Creating a scenario file with name " | sed -e 's/Creating a scenario file with name //')

# Remove autonomous_time from scenario file, so test_sdl is playback only
sed -i '/^autonomous_time:.*/d' $WORKSPACE/log_tests/scenarios/${scenarios_filename}.pbtxt

echo "Run command"
echo "$WORKSPACE/sim/sdl/test_sdl.sh --regenerate_perception //log_tests/scenarios/$scenarios_filename --output_chum_root=$CHUM_OUTPUT_ROOT --output_chum_variant=$CHUM_OUTPUT_VARIANT"
$WORKSPACE/sim/sdl/test_sdl.sh --regenerate_perception //log_tests/scenarios:$scenarios_filename --output_chum_root=$CHUM_OUTPUT_ROOT --output_chum_variant=$CHUM_OUTPUT_VARIANT
