#!/bin/bash
# Copyright (C) 2008-2018 Canonical, Ltd.
# Author: Emilia Torino <emilia.torino@canonical.com>
#
# This script attempts to build up statistics for a report on
# security update activity on USNs, and CVEs including Universe packages
# not present in USNs. The script requires UCT to be set.
#
# export UCT=$HOME/uct_dir
# $ $UCT/scripts/`basename $0` -r trusty -s 1556593200 -d
#
set -e
export LANG=C

help() {
    cat <<EOM
This script attempts to buildup statistics for a report on
security update activity on USNs, and CVEs including Universe packages
not present in USNs.

Typical usage:

Eg:
export UCT=$HOME/uct_dir
$ $UCT/scripts/`basename $0` -r trusty -s 1556593200 -d
EOM
}

since=0
before=$( date +%s )
details="no"
while getopts "hdr:s:b:" opt ; do
    case "$opt" in
        r) release_name="$OPTARG";;
        s) since="$OPTARG";;
        b) before="$OPTARG";;
        d) details="yes";;
        h) help ; exit 0;;
        ?) help ; exit 1;;
    esac
done

# validate required args
if [ -z "${release_name}" ]; then
    echo "Need to specify an Ubuntu release name when running this script. eg: trusty"
    help
    exit;
fi

ORIGINAL_IFS=$IFS
IFS=':'

# cd to $UCT directory if not there already
cd $UCT
#Get main USNs and CVEs stats.
MAIN_USNS_AND_CVES=$(./scripts/report-fixes-by-usn.py "${release_name}" --since "${since}" --before "${before}" --summary 2>&1)
while read -r line; do
  read -ra ADDR <<< "$line"
  if [ "${ADDR[0]}" == "CVEs" ]; then
    MAIN_CVES="${ADDR[1]}"
  elif [ "${ADDR[0]}" == "USNs" ]; then
    MAIN_USNS=${ADDR[1]}
  elif [ "${ADDR[0]}" == "USNs published for trusty" ]; then
    USNS="$line"
  fi
done <<< "$MAIN_USNS_AND_CVES"

#Universe CVEs are not present in USNs so we need to query them separately
UNIVERSE_CVES_INFO=$(./scripts/report_universe_cves.py "${release_name}" --since "${since}" --before "${before}"2>&1)
while read -r line; do
  read -ra ADDR <<< "$line"
  if [ "${ADDR[0]}" == "CVEs" ]; then
    UNIVERSE_CVES="${ADDR[1]}"
  fi
done <<< "$UNIVERSE_CVES_INFO"

#Merge both outputs and remove duplicates
MERGED_CVES_LIST=$(echo "$MAIN_CVES$UNIVERSE_CVES"  | xargs -n1 | sort -u | xargs)

IFS=$ORIGINAL_IFS
MAIN_CVES_AS_ARRAY=($MAIN_CVES)
UNIVERSE_CVES_AS_ARRAY=($UNIVERSE_CVES)
MERGED_CVES_AS_ARRAY=($MERGED_CVES_LIST)

printf "$USNS"
printf "\nCVEs published for main ${#MAIN_CVES_AS_ARRAY[@]}"
printf "\nCVEs published for Universe ${#UNIVERSE_CVES_AS_ARRAY[@]}"
printf "\nUnique CVEs published for main and Universe ${#MERGED_CVES_AS_ARRAY[@]}"
if [ "$details" = "yes" ]; then
  printf "\n\n USNs: $MAIN_USNS"
  printf "\n\n Unique CVES in main and Universe: $MERGED_CVES_LIST"
  printf "\n\n CVES in main: $MAIN_CVES"
  printf "\n\n CVES in Universe: $UNIVERSE_CVES\n"
fi
