#!/bin/sh

# Author: Jamie Strandboge <jamie@ubuntu.com>
# Author: Kees Cook <kees@ubuntu.com>
# Copyright (C) 2005-2019 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.

set -e

#
# Usage:
# ./scripts/pkg_status pkgname1 pkgname2 ...
#
# ./scripts/pkg_status -f pkgname1 pkgname2 ... (full listing)
#

help() {
    cat <<EOM
./scripts/pkg_status [-f] [-r REL] pkgname1 pkgname2 ...
EOM
}

showfull="no"
assigned=""
subproject=""
only_release=
skip_esm=
while getopts "hfrsaRS:" opt ; do
    case "$opt" in
        f) showfull="yes";;
        r) only_release="--no-retired --only-release=$OPTARG";;
        s) skip_esm="--skip-esm";;
	a) assigned="--show-assignee";;
	R) released_info="--show-released-version";;
	S) subproject="--subproject=$OPTARG";;
        h) help ; exit 0;;
        ?) help;;
    esac
done

if [ -z "$1" ]; then
	echo "Need to specific a source package name"
	exit 1
fi

pkgs=""
for p in "$@"; do
	echo "$p" | egrep '^[a-zA-Z0-9]' >/dev/null 2>&1 || continue
	pkgs="${pkgs} -p ${p}"
done
if [ "$showfull" = "yes" ]; then
	CVES=$(./scripts/ubuntu-table $only_release $skip_esm $subproject $assigned $released_info --supported $pkgs 2>/dev/null | sort -k 2 | grep -v '^ ' | awk '{print $1}')
	echo "$CVES" | xargs ./scripts/cve_status -f
else
	REPORT=$(./scripts/ubuntu-table $only_release $skip_esm $subproject $assigned $released_info --supported $pkgs 2>/dev/null)
	if [ -n "$REPORT" ]; then
		echo "$REPORT" | head -n1
		echo "$REPORT" | tail -n +2 | sort -n
	fi
fi
