#!/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
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 '/vendor/|\./proto/|.glide|/k8sfv/|/fv/' | \
	      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 }}' \
                    ./... | grep -v /vendor/ )
test ! -z "$test_pkgs"
echo "Packages with tests: $test_pkgs"

ginkgo -cover -covermode=count -coverpkg=${go_dirs} -keepGoing -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/felix/==' | \
  column -t
