#!/bin/bash

TEST_COVERAGE_THRESHOLD=80

function unittest() {
  CGO_ENABLED=0 go test ./... -coverprofile coverage.tmp -covermode atomic
  test_result=$?
  if [ $test_result -ne 0 ]; then
    echo "Unit tests failed"
    exit 1
  fi
  # Process-level signal and os.Exit wiring add no domain-level test confidence.
  grep -v '/cmd/vm-migration/' coverage.tmp >coverage.out
  go tool cover -func coverage.out
  echo "Quality Gate: checking test coverage is above threshold ..."
  echo "Threshold             : $TEST_COVERAGE_THRESHOLD%"
  totalCoverage=$(go tool cover -func=coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+')
  echo "Current test coverage : $totalCoverage %"
  if (($(echo "$totalCoverage $TEST_COVERAGE_THRESHOLD" | awk '{print ($1 >= $2)}'))); then
    echo "OK"
  else
    echo "Current test coverage is below threshold. Please add more unit tests or adjust threshold to a lower value."
    echo "FAIL"
    exit 1
  fi
}

if [ "$1" == "unittest" ]; then
  unittest
fi
