#!/usr/bin/env sh
set -eu

if ! set -o pipefail 2>/dev/null; then
  :
fi

SERVICE="${1:-}"
if [ -z "${SERVICE}" ]; then
  echo "usage: $0 <service-key>" >&2
  exit 2
fi

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)"
cd "${REPO_ROOT}"

if bypass_reason="$(sh "${SCRIPT_DIR}/should_bypass_backend_check.sh" "${SERVICE}" tests)"; then
  echo "[backend-tests] ${bypass_reason}"
  exit 0
fi

# shellcheck source=ci/scripts/common/backend_modules.sh
. "${SCRIPT_DIR}/backend_modules.sh"

if ! modules="$(backend_service_modules "${SERVICE}")"; then
  echo "[backend-tests] unknown service key: ${SERVICE}" >&2
  exit 2
fi

run_go_tests() {
  module="$1"
  if [ ! -f "${module}/go.mod" ]; then
    echo "[backend-tests] missing go.mod for module: ${module}" >&2
    exit 1
  fi

  echo "[backend-tests] running go test ./... in ${module}"
  (
    cd "${module}"
    go test ./...
  )
}

for module in ${modules}; do
  run_go_tests "${module}"
done
