#!/bin/bash

# Author: Jamie Strandboge <jamie@ubuntu.com>
# Author: Kees Cook <kees@ubuntu.com>
# Author: Marc Deslauriers <marc.deslauriers@ubuntu.com>
# Author: Steve Beattie <sbeattie@ubuntu.com>
# 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.

set -e

#
# Usage:
# ./scripts/cve_need_retire [-p]
#

cvedir="./active"

help() {
    cat <<EOM
Uasge: cve_need_retire [-f] [-p] [-u]"

  -f	full listing
  -r	report (first) package
  -p	list path to CVE
  -u	move the files to retired directory
  -c	commit the changes to git (requires -u)
  -h	this help statement
EOM
}

full=
update=
commit=
path=
report_pkg=

while getopts "fhucpr" opt ; do
    case "$opt" in
        f) full="yes";;
        u) update="yes";;
        c) commit="yes";;
        p) path="$cvedir/";;
        r) report_pkg="yes";;
        h) help ; exit 0;;
        ?) help ; exit 1;;
    esac
done

vcs=bzr
if [ -d ".git" ]; then
    vcs=git
fi

if [ -n "${commit}" ] && [ -z "${update}" ] ; then
    echo "commit option (-c) requires update option (-u)"
    echo
    help
    exit 1
fi

./scripts/ubuntu-table 2>&1 >/dev/null | grep '^retire: ' | while read junk cve
do
    if [ -z "$full" ]; then
        if [ -z "$update" ]; then
            if [ -z "$report_pkg" ] ; then
                echo "$path$cve"
            else
                first_pkg=$(grep -m1 '^upstream_' "active/$cve" | cut -d _ -f2 | cut -d : -f1)
                echo "$path$cve: $first_pkg"
            fi
        else
            $vcs mv -v "active/$cve" retired
        fi
    else
        cat "$cvedir/$cve"
        echo "--"
    fi
done

if [ -n "$update" ] && [ "$vcs" = "git" ] ; then
    count=$(git diff --cached --name-only --diff-filter=AMR HEAD | grep -c retired)
    changes=$(git diff --cached --name-only --diff-filter=AMR HEAD | grep retired | xargs grep -h '^Patches_'  | cut -d_ -f2 | tr -d : | sort | uniq -c | awk '{ printf("%s(%s)\n", $2, $1) }' | fmt -w70 | sed -e 's/^/  /')
    if [ "${count}" = "1" ] ; then
        message="$(printf "Retired 1 CVE\n\nPackages affected:\n%s\n" "${changes}")"
    else
        message="$(printf "Retired %s CVEs\n\nPackages affected:\n%s\n" "${count}" "${changes}")"
    fi

    if [ -z "${commit}" ] ; then
        echo "${message}"
    else
        git commit -sem "${message}"
    fi
fi
