#!/bin/bash
set -o errexit -o nounset -o pipefail
[[ "${TRACE:-0}" == "1" ]] && set -o xtrace

##
# Formats CVE results in a markdown table to display a summary in a GitHub Action UI
##

# Check if the number of arguments is correct
if [ $# -ne 1 ]; then
    echo "Usage: $0 <filename of grype json results>"
    exit 1
fi

_results_filename="${1}"

# Check if the file exists
if [ ! -f "${_results_filename}" ]; then
    echo "Error: File '${_results_filename}' does not exist"
    exit 1
fi

_number_of_cves_found=$(jq -r '.matches | length' "${_results_filename}")

echo -e "# CVE Scan Results\n"

if [ ${_number_of_cves_found} -eq 0 ]; then
    echo -e "## Success! No vulnerabilities found.\n"
else
    echo -e "## Failure: ${_number_of_cves_found} vulnerabilities found.\n"

    _table_headers='"NAME","INSTALLED","FIXED-IN","TYPE","VULNERABILITY","SEVERITY"'
    _table_underlines='"----","---------","--------","----","-------------","--------"'

    jq -r "[${_table_headers}],
    [${_table_underlines}],
    (.matches[] | [
        .artifact.name,
        .artifact.version,
        .vulnerability.fix.versions[0],
        .artifact.type,
        .vulnerability.id,
        .vulnerability.severity
    ]) | @tsv" "${_results_filename}" \
    | sed 's/|/\\|/g' \
    | sed 's/\t/ | /g'
fi