#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (c) 2024 - Greg Kroah-Hartman <gregkh@linuxfoundation.org>
#
# cve_publish_json - Publish all existing json entries to the CVE database
#
# Will look through the list of all published cve ids and publish them with the
# CVE database.  It is recommended to do this after new entries are created,
# and after updating existing ones.
#
# Note, this publishes ALL of them, we should only publish those that have
# changed, that will be added later...
#
# This is good to do after older stable kernels have been released as often
# CVEs are included in older stable kernels AFTER they show up in newer ones,
# and this keeps the database at CVE more up to date and friendly for others to
# rely on.  The mbox files generally shouldn't be resent, as that's just noise
# that no one wants to see.
#
# Usage:
#	cve_publish
#
# Requires:
#  cve


# FIXME: Is only using the test database for now.


# don't use unset variables
set -o nounset

# set where the tool was run from,
# the name of our script,
# and the git version of it
DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
SCRIPT=${0##*/}
SCRIPT_VERSION=$(cd "${DIR}" && git show -s --abbrev-commit --abbrev=12 --pretty=format:"%h")

help() {
	echo "${SCRIPT}"
	exit 1
}

cd "${DIR}"/../ || exit 1

# Get a list of the json files that are modified in some way (not deleted) and
# only submit those to the system, cutting down on round trips
files=$(git status -s | grep -v "^ D" | awk '{print $2}' | grep "\.json$" )
for file in ${files}; do
	cve=$(echo "${file}" | cut -f 1 -d '.' | cut -f 4 -d '/')
	root=$(echo "${file}" | cut -f 1 -d '.' )
	sha_file="${root}.sha1"
	sha=$(cat "${sha_file}")
	#echo "file=${file} cve=${cve} sha_file=${sha_file} sha=${sha}"
	#echo "id=${id} sha=${sha} cve=${cve}"

#	if cve -o Linux list | grep ${cve} | grep -q PUBLISHED; then
#		echo -n "${cve} is already published - are you sure you wish to update it (N/y)? "
#		read choice
#		if [[ ${choice} != "y" && ${choice} != "Y" ]]; then
#			continue
#		fi
#	fi

	echo "Uploading ${cve} for commit ${sha}"
	cve -o Linux publish "${cve}" -f "${root}.json"
	good=$?
	if [[ "${good}" == 0 ]]; then
		echo "CVE published successfully at: https://cve.org/CVERecord/?id=${cve}"
	else
		echo "ERROR: Something went wrong submitting ${cve}"
	fi
	echo ""
	#cve -u gregkh@linuxfoundation.org -o Linux -e test publish ${cve} -f "${root}.json"
done

# to list all published entries:
# cve -u gregkh@linuxfoundation.org -o Linux -e test list
