#!/usr/bin/env bash

set -e
set -x

echo "Removing old coverprofiles..."
find . -name "*.coverprofile" -type f -delete

echo "Calculating packages to cover..."
go_dirs=$(find -type f -name '*.go' | \
	      grep -vE '\./proto/|.glide|check-licenses|cmd/typha-client|\.go-pkg-cache' | \
	      xargs -n 1 dirname | \
	      sort | uniq | \
	      tr '\n' ',' | \
	      sed 's/,$//' )
echo "Covering: $go_dirs"
test ! -z "$go_dirs"

test_pkgs=$(go list -f '{{ if .TestGoFiles | or .XTestGoFiles }}{{ .ImportPath }}{{ end }}' \
                    ./... )
test ! -z "$test_pkgs"
echo "Packages with tests: $test_pkgs"

ginkgo -cover -covermode=count -coverpkg=${go_dirs} ${GINKGO_ARGS} -r
gocovmerge $(find . -name '*.coverprofile') > combined.coverprofile

# Print the coverage.  We use sed to remove the verbose prefix and trim down
# the whitespace.
go tool cover -func combined.coverprofile | \
  sed 's=github.com/projectcalico/typha/==' | \
  column -t
