#!/bin/bash

set -euo pipefail

workspace="$(bazel info workspace)"
BASE_PATH="$workspace"/sim/sim_tests/unstructured_stress_tests/base_scenarios
OUTPUT_PATH="$workspace"/sim/sim_tests/unstructured_stress_tests/generated_tests

generate_tests() {
  rm -f "$OUTPUT_PATH"/placeholder.pbtxt
  bazel run //sim/sim_tests/unstructured_stress_tests/tools:generate_tests -- --config_file "$1" --output_dir "$2"
}

select_tests() {
  while :
do
    clear
    cat<<EOF
================================
Unstructured Stress Tests Helper
--------------------------------
(1) Pedestrian
(2) Following
(3) Cut-in Constraint
(R) [Return]
--------------------------------
EOF
    read -n1 -s
    case "$REPLY" in
    "1")
      generate_tests "$BASE_PATH"/pedestrian/scenario_scaling_config.pbtxt "$OUTPUT_PATH"
      break
      ;;
    "2")
      generate_tests "$BASE_PATH"/follow/scenario_scaling_config.pbtxt "$OUTPUT_PATH"
      break
      ;;
    "3")
      generate_tests "$BASE_PATH"/cut_in_constriant/scenario_scaling_config.pbtxt "$OUTPUT_PATH"
      break
      ;;
    "R")  break ;;
    "r")  break ;;
     * )  echo "invalid option" ;;
    esac
    sleep 0.25
done
}

clean_generated() {
  rm -f "$OUTPUT_PATH"/*.pbtxt
  touch "$OUTPUT_PATH"/placeholder.pbtxt
  echo "All generated tests have been removed."
  sleep 0.5
}

schedule_run() {
  "$workspace"/sim/launch.sh pipedream planner //sim/sim_tests/unstructured_stress_tests/generated_tests:generated_tests_all
}

while :
do
    clear
    cat<<EOF
================================
Unstructured Stress Tests Helper
[Total Generated]: $(find $OUTPUT_PATH -maxdepth 1 -name '*.pbtxt' -not -name "placeholder.pbtxt" | wc -l)
--------------------------------
(1) Generate Tests
(2) Clean Generated Tests
(3) Run Generated Tests
(Q) Quit
--------------------------------
EOF
    read -n1 -s
    case "$REPLY" in
    "1")  select_tests ;;
    "2")  clean_generated;;
    "3")
      schedule_run
      exit
      ;;
    "Q")  exit ;;
    "q")  exit ;;
     * )
     echo "invalid option"
     sleep 0.25
     ;;
    esac
    sleep 0.25
done
