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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
build_dir="${repo_root}/build"
gopath_bin="$(go env GOPATH)/bin"
junit_report="${gopath_bin}/go-junit-report"

run_with_retry() {
  local attempts="$1"
  shift
  local try=1
  local delay=3
  local rc=0
  while true; do
    "$@" && return 0
    rc=$?
    if [[ "${try}" -ge "${attempts}" ]]; then
      return "${rc}"
    fi
    echo "[quality] retry ${try}/${attempts} after rc=${rc}: $*" >&2
    sleep "${delay}"
    delay=$((delay * 2))
    try=$((try + 1))
  done
}

mkdir -p "${build_dir}"

if [ ! -x "${junit_report}" ]; then
  run_with_retry 3 go install github.com/jstemmer/go-junit-report/v2@latest
fi

cd "${repo_root}"
export GOPROXY="${GOPROXY:-https://proxy.golang.org,direct}"
run_with_retry 4 go mod download

set +e
run_with_retry 3 go test -v -count=1 -coverprofile="${build_dir}/coverage.out" ./... > "${build_dir}/test.out" 2>&1
test_rc=$?
set -e

printf '%s\n' "${test_rc}" > "${build_dir}/test.exitcode"
cat "${build_dir}/test.out"
"${junit_report}" < "${build_dir}/test.out" > "${build_dir}/junit.xml"

coverage="0"
if [ -f "${build_dir}/coverage.out" ]; then
  coverage="$(go tool cover -func="${build_dir}/coverage.out" | awk '/^total:/ {gsub("%","",$3); print $3}')"
fi
printf '{"summary":{"percent_covered":%s}}\n' "${coverage}" > "${build_dir}/coverage.json"

python "${repo_root}/scripts/publish_test_metrics.py"

if [ "${test_rc}" -ne 0 ]; then
  exit "${test_rc}"
fi

cd "${repo_root}/testing"
METIS_USE_EXISTING_COVERAGE=1 go test -count=1 -v ./...
