#!/bin/bash

set -e

if [ -z $SKIP ]
then
  # We skip the 'tests' directory because there are no buildable go source files.
    SKIP="vendor,tests"
else
    SKIP="vendor,tests,$SKIP"
fi

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

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

# Run tests in random order find tests recursively (-r).
echo WHAT: $WHAT
echo SKIP: $SKIP
echo GINKGO_ARGS: $GINKGO_ARGS
ginkgo -cover -coverpkg=${go_dirs} -r --skipPackage $SKIP $WHAT $GINKGO_ARGS
gocovmerge $(find . -name '*.coverprofile') > combined.coverprofile

echo
echo '+==============+'
echo '| All coverage |'
echo '+==============+'
echo
go tool cover -func combined.coverprofile | \
  sed 's=github.com/projectcalico/kube-controllers/==' | \
  column -t

echo
echo '+==================+'
echo '| Missing coverage |'
echo '+==================+'
echo
go tool cover -func combined.coverprofile | \
  sed 's=github.com/projectcalico/kube-controllers/==' | grep -v '100.0%' | \
  column -t
