set -e

ISTANBUL_COMBINE_OUTPUT=`./node_modules/.bin/istanbul-combine -d coverage -p summary -r lcov -r html packages/frint*/coverage/coverage*.json`;

LINES_COVERAGE_ORIGINAL_LINE=`echo "${ISTANBUL_COMBINE_OUTPUT}" | grep Lines`;
LINES_COVERAGE_PERCENTAGE=`echo "${LINES_COVERAGE_ORIGINAL_LINE}" | awk '{print $3}' | tr -d '[:space:]' | tr -d '%'`;

EXPECTED_LINES_COVERAGE_PERCENTAGE=${EXPECTED_LINES_COVERAGE_PERCENTAGE:-$1};
EXPECTED_LINES_COVERAGE_PERCENTAGE=${EXPECTED_LINES_COVERAGE_PERCENTAGE:-50};

COMPARISON_RESULT=`echo "${LINES_COVERAGE_PERCENTAGE} < ${EXPECTED_LINES_COVERAGE_PERCENTAGE}" | bc -l`

if [ $COMPARISON_RESULT -eq 1 ]; then
  LINES_COVERAGE_ORIGINAL_LINE_IN_RED=`echo "\033[0;31m${LINES_COVERAGE_ORIGINAL_LINE}\033[0m"`;

  echo "Current lines coverage (${LINES_COVERAGE_PERCENTAGE}) is lower than the minimum expected (${EXPECTED_LINES_COVERAGE_PERCENTAGE}%)";
  echo "${ISTANBUL_COMBINE_OUTPUT/${LINES_COVERAGE_ORIGINAL_LINE}/${LINES_COVERAGE_ORIGINAL_LINE_IN_RED}}";
  exit 1;
fi

echo "$ISTANBUL_COMBINE_OUTPUT";
