#!/usr/bin/env bash
set -euo pipefail

# Locate the workspace root once so we can reference it in test cases.
script_dir="$(dirname "$(readlink --canonicalize "${BASH_SOURCE[0]}")")"
workspace_root="$(builtin cd "$script_dir" && git rev-parse --show-toplevel)"
readonly script_dir workspace_root

function test_case() {
  echo "TEST CASE: $1"
  shift

  local compile_commands_script compile_commands_args
  compile_commands_script=./tools/aspects/compile_commands/compile_commands.py
  compile_commands_args=
  compile_commands_args+=" --loglevel=debug"
  compile_commands_args+=" --output_dir=$(mktemp --directory)"
  compile_commands_args+=" --output_strategy=replace"
  readonly compile_commands_script compile_commands_args

  builtin cd "$workspace_root"
  "$compile_commands_script" $compile_commands_args "$@"
}

function main() {
  test_case \
    "Run against a single relative file" \
    --filename=vehicle/common/proto/herostate.cpp \
    --workspace_root="$workspace_root"

  test_case \
    "Run against a single absolute file" \
    --filename="$workspace_root/vehicle/common/proto/herostate.cpp"

  test_case \
    "Run against a whole package" \
    --filename=vehicle/common/proto/herostate.cpp \
    --workspace_root="$workspace_root" \
    --target_full_package

  test_case \
    "Run against a whole package and transitive dependencies" \
    --filename=vehicle/common/proto/herostate.cpp \
    --workspace_root="$workspace_root" \
    --no_build_generated \
    --target_full_package \
    --target_transitive

  test_case \
    "Run against a single target" \
    --targets //vehicle/common/proto:hero_state \
    --workspace_root="$workspace_root"

  test_case \
    "Run against a single target and transitive dependencies" \
    --targets //vehicle/common/proto:hero_state \
    --workspace_root="$workspace_root" \
    --target_transitive

  test_case \
    "Run against all targets" \
    --all \
    --workspace_root="$workspace_root" \
    --no_build_generated

  test_case \
    "Run in CUDA mode against a single target" \
    --targets //vehicle/perception/perception_runner \
    --workspace_root="$workspace_root" \
    --ignore_assemble_database_failure \
    --build_options='--config=cuda'

  test_case \
    "Run in CUDA mode against a whole package and transitive dependencies" \
    --filename=vehicle/perception/perception_runner/perception_runner.cpp \
    --workspace_root="$workspace_root" \
    --target_full_package \
    --target_transitive \
    --no_build_generated \
    --ignore_assemble_database_failure \
    --build_options='--config=cuda'
}

main
