#! /bin/bash
# Copyright 2023 Google LLC
#
# 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.

# `-e` enables the script to automatically fail when a command fails
set -e

# Calculate total coverage, skipping the generated protobuf file.
# The CSV file generated by Jacoco has the test coverage for each. We use AWK to process this CSV file.
# here's what the AWK program means:
#
#     NR > 1 &&                                   Skip the first line, it only has field names
#       $3 != "com.google.cloud.sql.core.mdx"     Skip any line for class in the protobuf generated package 'mdx'
#     { covered += $6; total += $6+$5; }          For each line add a running sum of covered lines and total lines
#     END { printf "%2.f", covered/total * 100}'  At the end, print out the coverage percentage, no decimals
#

CUR_COVER=$( awk -F,  \
  'NR > 1 && $3 != "com.google.cloud.sql.core.mdx" { covered += $6; total += $6+$5; } END { printf "%2.f", covered/total * 100}' \
  < "core/target/site/jacoco/jacoco.csv")

if [ "$CUR_COVER" -lt 75  ]; then
  echo "FAIL: Current Coverage is $CUR_COVER%, less than the required 75%"
  exit 1;
else
  echo "PASS: Current Coverage is $CUR_COVER%"
fi
