#!/bin/sh

# Author: Jamie Strandboge <jamie@ubuntu.com>
# Copyright (C) 2013 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

showfull="no"
release=
showstatus="no"
activeonly="no"

help() {
  echo "Usage: ./scripts/pkg_history [-f] [-r release] pkgname1 pkgname2 ..."
  echo "   or: ./scripts/pkg_history -s -r release pkgname1 pkgname2 ..."
  exit $1
}

while getopts "ahfr:s" opt; do
   case "$opt" in
       f) showfull="yes";;
       r) release="$OPTARG";;
       s) showstatus="yes";;
       a) activeonly="yes";;
       h) help 0;;
       ?) help 1;;
   esac
done

if [ "$showstatus" = "yes" ]; then
    if [ -z "$release" ]; then
        help 2
    fi
    if [ "$showfull" = "yes" ]; then
        help 3
    fi
fi

shift $((OPTIND - 1))

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

for pkg in "$@"; do
    pattern="_${pkg}: "
    if [ -n "$release" ]; then
        pattern="${release}${pattern}"
    fi

    echo "= $pkg ="
    dirs="retired ignored active"
    if [ "${activeonly}" = "yes" ] ; then
    	dirs="active"
    fi
    for d in ${dirs} ; do
        for cve in `grep "$pattern" ./$d/CVE-* | \
            cut -d ':' -f 1 | \
            cut -d '/' -f 3 | \
            sort -u` ; do
            if [ "$showfull" = "yes" ]; then
                echo ""
                cat "./$d/$cve"
                echo ""
            else
                if [ "$showstatus" = "yes" ]; then
                    status=$(grep "^$pattern" "./${d}/${cve}" | cut -d ':' -f 2-)
                    echo "${cve}${status}"
                else
                    echo "$cve"
                fi
            fi
        done
    done
    if [ "$showfull" = "no" ]; then
        echo ""
    fi
done
