#!/bin/bash

lcovFilePath="./coverage/lcov.info"

# Read lcov.info
if [ ! -f "$lcovFilePath" ]; then
    echo "Error: $lcovFilePath not found."
    exit 1
fi

totalLines=0
coveredLines=0

while read -r line; do
    if [[ "$line" == "LF:"* ]]; then
        found=$(echo "$line" | cut -d':' -f2)
        totalLines=$((totalLines + found))
    elif [[ "$line" == "LH:"* ]]; then
        hit=$(echo "$line" | cut -d':' -f2)
        coveredLines=$((coveredLines + hit))
    fi
done <"$lcovFilePath"

# Calculate coverage percent
if [ "$totalLines" -ne 0 ]; then
    coveragePercentage=$(echo "scale=2; ($coveredLines / $totalLines) * 100" | bc)
    coveragePercentage=$(printf "%.0f" "$coveragePercentage")
else
    coveragePercentage=0
fi

# Update README.md
updateReadme() {
    local readmePath="./README.md"
    local badgeRegex="(https://img.shields.io/badge/unit_test_coverage-)[0-9.]+(%25-brightgreen)"
    local badgeURL="https://img.shields.io/badge/unit_test_coverage-${coveragePercentage}%25-brightgreen"

    # Read current content of README.md
    readmeContent=$(<"$readmePath")

    # Replace coverage percent before the '%' character in the badge
    newReadmeContent=$(echo "$readmeContent" | sed -E "s|${badgeRegex}|${badgeURL}|")

    # Overwrite README.md file with the modified content
    echo "$newReadmeContent" >"$readmePath"
}

updateReadme

echo "Coverage percent: ${coveragePercentage}%"
