#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
#
# Copyright (c) 2024 - Greg Kroah-Hartman <gregkh@linuxfoundation.org>
#
# cve_search - Search the published CVE records for the specified git id, or
# for the git id of a specified CVE
#
# If it is found, the CVE id or the git id is returned.
# If it is not found, returns an error.
#
# Usage:
#	cve_search [GIT_ID]
#
# Requires:
#  A kernel git tree with the SHA to be used in it

KERNEL_TREE=${CVEKERNELTREE}

if [ ! -d "${KERNEL_TREE}" ]; then
       echo "CVEERNELTREE needs setting to the stable repo directory"
       echo "Either manually export it or add it to your .bashrc/.zshrc et al."
       echo "See HOWTO in the root of this repo"
       exit 1
fi


# Colors are good!
if [[ -t 1 ]]; then
	txtred=$(tput setaf 1)		# Red
	txtgrn=$(tput setaf 2)		# Green
	txtblu=$(tput setaf 4)		# Blue
	txtcyn=$(tput setaf 6)		# Cyan
	txtrst=$(tput sgr0)		# Text reset
else
	txtred=""
	txtgrn=""
	txtblu=""
	txtcyn=""
	txtrst=""
fi

# 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##*/}

help() {
	echo "${SCRIPT} [GIT_ID]"
	exit 1
}

STRING="${1:-}"
if [[ "${STRING}" == "" ]] ; then
	help
fi

CVE_ROOT="${DIR}/../cve/"

# Treat the string as a SHA1 first:

# See if the SHA given to us is a valid SHA in the git repo
# and turning the sha into a "full" one so that we don't get this wrong.
GIT_SHA_FULL=$(cd "${KERNEL_TREE}" && git log -1 --format="%H" "${STRING}" 2> /dev/null)
if [[ "${GIT_SHA_FULL}" != "" ]] ; then
	# it's a sha, let's search for that!
	found=$(grep -r -l "${STRING}" "${CVE_ROOT}"/published/ "${CVE_ROOT}"/rejected/ | grep "sha1")
	if [[ "${found}" != "" ]]; then
		cve=$(basename "${found}" | cut -f 1 -d '.')
		echo "${txtcyn}${cve}${txtrst} is assigned to git id ${txtgrn}${STRING}${txtrst}"
		exit 0
	fi
	# sha not found, so error out
	echo "git sha1 ${STRING} not found in any CVE record, sorry."
	exit 1
fi

# Treat the string as a CVE id
# NOTE, not the best search, we can have false-positives here, like searching
# just for "25162" or "2019-25162" or the like.  We should really parse this
# out to verify it is in CVE-YYYY-ID format, but oh well, that's for
# tomorrow...
found=$(find "${CVE_ROOT}/" -type f | grep -v testing | grep "${STRING}\$")
if [[ "${found}" != "" ]]; then
	sha=$(cat "${found}.sha1")
	echo "${txtcyn}${STRING}${txtrst} is assigned to git id ${txtgrn}${sha}${txtrst}"
        exit 0
fi

echo "${STRING} not found in any CVE record, sorry."
exit 1
