#!/bin/sh

# Copyright (C) 2005-2020 Canonical Ltd.
#
# This script is distributed under the terms and conditions of the GNU General
# Public License, Version 2 or later. See http://www.gnu.org/copyleft/gpl.html
# for details.
#
# This script reports the status of CVE IDs passed as arguments to the
# script.

set -e
#
# Usage:
# ./scripts/cve_status CVE-XXXX-XXXX CVE-XXXX-XXXX
#

if [ "$1" = "-h" ]; then
	echo "./scripts/cve_status [-f] CVE-XXXX-XXXX CVE-XXXX-XXXX ..."
	exit 0
fi

just_status=yes
if [ "$1" = "-f" ]; then
	shift || true
	just_status=""
fi

if [ -z "$1" ]; then
	echo "Need to specify a CVE"
	exit 1
fi

pyexe="python"
if command -v python3 >/dev/null ; then
    pyexe="python3"
fi

oldest_release=$(PYTHONPATH="${PYTHONPATH}${PYTHONPATH:+:}$(dirname "$0")" "$pyexe" -c 'import cve_lib ; print(cve_lib.oldest_supported_release());' | sed 's#/esm#/e#g')

HEADER_SEEN=
for c in "$@"
do
	c=$(echo "$c" | sed 's/[,:]//g')
	echo "$c" | grep -E '^[0-9][0-9][0-9][0-9]\-[0-9][0-9][0-9][0-9][0-9]*$' >/dev/null 2>&1 && c="CVE-$c"
	echo "$c" | grep -E '^(CVE|EMB)-' >/dev/null 2>&1 || continue
	if [ -s "./retired/${c}" ]; then
		echo "$c (retired)"
		if [ -z "$just_status" ]; then
			echo ""
			cat "./retired/$c"
			echo ""
		fi
	elif [ -s "./ignored/${c}" ]; then
		echo "$c (ignored)"
		if [ -z "$just_status" ]; then
			echo ""
			cat "./ignored/$c"
			echo ""
		fi
	elif sed -e 's/#.*//' ./ignored/not-for-us.txt | grep -F -q "$c" ; then
		echo "$c (not for us)"
	elif [ -L "./embargoed" ] && [ -s "./embargoed/$c" ]; then
		echo "$c (embargoed)"
		if [ -z "$just_status" ]; then
			echo ""
			cat "./embargoed/$c"
			echo ""
		fi
	elif [ -s "./active/$c" ]; then
		TABLE=$(./scripts/ubuntu-table --supported 2>/dev/null)
		REPORT=$(echo "$TABLE" | grep -E "$c")
		LINES=$(echo "$REPORT" | wc -l)
		if [ "$LINES" -gt 0 ] && [ -z "$HEADER_SEEN" ]; then
                        echo "$TABLE" | grep -E "[[:space:]]+$oldest_release"
			HEADER_SEEN="yes"
		fi
		echo "$REPORT"
		if [ -z "$just_status" ]; then
			echo ""
			cat "./active/$c"
			echo ""
			# Need header again since CVE dump breaks continuity
			HEADER_SEEN=
		fi
	else
		echo "$c (not found)"
	fi
done

