#!/usr/bin/env bash

# Copyright (c) 2017-2018 Tigera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# Remove the old profiles.
find . -name "*.coverprofile" -type f -delete

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

test_pkgs=$(go list -buildvcs=false -f '{{ if .TestGoFiles | or .XTestGoFiles }}{{ .ImportPath }}{{ end }}' \
                    ./... | grep -v /vendor/ )
test ! -z "$test_pkgs"

if [ "$#" -eq 0 ]; then
  # Only log out the packages if we've not been given an override
  # argument.
  echo "Packages with tests: $test_pkgs"
fi

set -x
ginkgo -cover -covermode=count -coverpkg=${go_dirs} -keepGoing -r "$@"
set +x

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/felix/==' | \
  column -t | grep -v --perl -e '\b0\.0%|\binit\b'

echo "(hiding uncovered functions and init functions)"
