#!/bin/bash

# Copyright 2011 Florian Philipp
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

source /etc/make.globals
source /etc/make.conf

getInstalled() {
# Output a list of all packages installed from the normal portage tree.
# Overlays are ignored because their changelog format might be incompatible.
# The version number and revision are removed, as well.
    find /var/db/pkg -maxdepth 3 -name repository -print0 |
    xargs -0 --no-run-if-empty grep --files-with-matches '^gentoo$' | \
	awk --field-separator '/' '{printf "%s/%s\0", $(NF-2), $(NF-1) }' | \
	xargs -0 --no-run-if-empty qatom | \
	cut --delimiter=' ' --fields=1,2 --output-delimiter='/' | uniq
}

catPackages() {
    awk --assign "PORTDIR=$PORTDIR" '{printf "%s/%s/ChangeLog\0", PORTDIR, $0}' | \
	xargs -0 --no-run-if-empty cat --
}

chompLines() {
# Read changelog file and change format so that each change is a single
# line instead of changes being separated by empty lines.
# To do this, replace newlines with tabs and tabs with spaces, so that sed
# can be applied to one extremely long line.. What previously was an empty line,
# now appears as consecutive tabs. Replace them with newlines and then transform
# all remaining tabs into spaces.
    tr '\t\n' ' \t' | sed 's/\t\t\t*/\n/g' | tr '\t' ' '
}

extractSecurity() {
# Lines starting with * contain a full ebuild name followed by lines
# containing changes on that build.
# Extract commit messages for security bugs and print them in the form "package name\t message"
    awk 'BEGIN{package="*UNDEFINED PACKAGE"}
	{ if ($0 ~ /^*/) package=$0;
else if ($0 ~ /security bug/) printf "%s\t%s\n", package, $0 }'
}

arrangeForDelimit() {
    local delimiterLine="$1"
# Each commit message begins with a date string.
# Each complete line is expected to be in the form "{ebuild}\t{date}; {message}
# Rearrange each line so that the date string is in the beginning
    sed 's/^\([^\t]*\t\)\([^;]*; \)\(.*\)/\2\1\3/'
# Append the delimiter to the list of commits
    echo "$delimiterLine"
}

sortByDate() {
# Sort by year, then month, then day of month, descending
    LC_ALL=C sort --key=3,3nr --key=2,2Mr --key=1,1nr 
}

headToDelimiter() {
    local delimiterLine="$1"
# Output everything up to the delimiter
    sed -n "s/^${delimiterLine}//; T print; q; :print; p"
}

prettyPrint() {
# Remove repeated whitespace, whitespace at the line start transform the
# semicolon after the date into a tab so that the format is nicely tab separated.
    sed 's/   */ /g; s/^ //; s/\; /\t/'
}

printUsage() {
    echo -e "Usage: $0 [-d {days}] [-w {weeks}] [-m {months}] {-y {years}]\n" \
	'where days weeks months and years define how far back to look for' \
	'security fixes. Defaults to 1 week.'
}

declare -i days=0 weeks=0 months=0 years=0
while getopts 'd:w:m:y:' opt "$@"; do
    case "$opt" in
        '?' )
            printUsage
	    exit 1;;
        'd' )
	    days=-1*"${OPTARG}";;
        'w' )
	    weeks=-1*"${OPTARG}";;
        'm' )
	    months=-1*"${OPTARG}";;
        'y' )
	    years=-1*"${OPTARG}";;
    esac
done

if (( days | weeks | months | years == 0 )); then
    weeks=-1
fi

cutoffDate=$(LC_ALL='C' date --universal \
    --date="$days days $weeks weeks $months months $years years" '+%d %b %Y')
DELIMITER='#####'
delimiterLine="$cutoffDate; $DELIMITER"
getInstalled | \
    catPackages | \
    chompLines  | \
    extractSecurity | \
    arrangeForDelimit "$delimiterLine" | \
    sortByDate | \
    headToDelimiter "$delimiterLine" | \
    prettyPrint
