#!/bin/bash

TEST_COVERAGE_THRESHOLD=63

function unittest() {
  CGO_ENABLED=0 go test ./... -coverprofile coverage.tmp -covermode count
  test_result=$?
  if [ $test_result -ne 0 ]; then
    echo "Unit tests failed"
    exit 1
  fi
  cat coverage.tmp | grep -v '/loader' | grep -v '/consts' | grep -v '/testkits' | grep -v '/metadata' | grep -v '/api' | grep -v '/pkg/agentcontrol' | grep -v '/pkg/o11y' >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
