#!/bin/sh

# check_pkg_deny_list checks if a package being scanned is in the deny list of
# packages not to be VEXed.
# The first param is the package to be checked with its full source address.
# E.g., github.com/my_org/my_pkg .
check_pkg_deny_list() {
    local pkg="${1}"
    if grep -q "^${pkg}$" "${REPOS_DENY_LIST}"; then
        true
    else
        false
    fi
}

# fatal() is used to exit on error operations executed inside subshells. We use
# a sleep to make sure that the parent shell has time to catch the error
# exception and exit as soon as possible. Otherwise we risk the execution to
# continue until the parent shell caught up to it. This is needed, because we
# rely too much on subshells.
fatal() {
    echo "[ERROR] killing process..."
    kill -9 "${PPID}"
    sleep 5
}

# merge_cve_csv() merges two VEX CVE .csv files into one, sorting and
# deduplicating repeated entries.
merge_cve_csv() {
    local main_csv_file="${1}"
    local scan_csv_file="${2}"
    local tmp_csv_file=$(mktemp)

    cat "${main_csv_file}" "${scan_csv_file}" | grep -v "${VEX_CSV_HEADER}" | \
        sort | sort -u > "${tmp_csv_file}" || true

    echo "${VEX_CSV_HEADER}" > "${main_csv_file}"
    cat "${tmp_csv_file}" >> "${main_csv_file}"
    rm -rf "${tmp_csv_file}"
}

# merge_cve_files() merges the individual and automated VEX CVE .csv files into
# the main .csv file. This file acts as a central database of the VEXed CVES.
merge_cve_files() {
    merge_cve_csv "${VEX_CVES_CSV}" "${VEX_CVES_AUTOMATED_CSV}"
    merge_cve_csv "${VEX_CVES_CSV}" "${VEX_CVES_MANUAL_CSV}"
}

