#!/usr/bin/env bash

# This script just examines all the lines from the go test coverprofile output.
# It gets the total number of lines, and the total number of lines that were
# executed more than once.
# It then compares a that fraction against a target coverage fraction, printing
# out the two values, and giving a bad exit code if the measured coverage is
# not better than the target coverage.

TARGETCOVERAGE=0.7

TOTALLINES=`awk '{ sum += $2 } END { print sum }' coverage-all.out`
COVEREDLINES=`awk '{ sum += ($3 != 0 ? $2 : 0) } END { print sum }' coverage-all.out`
UNCOVEREDLINES=$(awk "BEGIN {printf \"%d\",${TOTALLINES}*${TARGETCOVERAGE}-${COVEREDLINES}+1}")
rm coverage-all.out
COVERAGEPERCENT=$(awk "BEGIN {printf \"%.2f\",${COVEREDLINES}/${TOTALLINES}*100}")
TARGETCOVERAGEPERCENT=$(awk "BEGIN {printf \"%.2f\",${TARGETCOVERAGE}*100}")
COVERAGEPERCENTX10=$(awk "BEGIN {printf \"%d\",${COVEREDLINES}/${TOTALLINES}*1000}")
TARGETCOVERAGEPERCENTX10=$(awk "BEGIN {printf \"%d\",${TARGETCOVERAGE}*1000}")
echo "Across all packages, code is $COVERAGEPERCENT% covered; target is $TARGETCOVERAGEPERCENT%."
[[ $COVERAGEPERCENTX10 < $TARGETCOVERAGEPERCENTX10 ]] && echo -e 'Code covegage value is too low\nadd coverage to '$UNCOVEREDLINES' lines' && exit 1
exit 0
