#!/bin/bash -e

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

#
# USAGE:
# scripts/html-report -d ~/public_html/cve
# scripts/html-report -d ~/public_html/cve -S
#
# '-d' specifies the output directory for the html
#

if [ "$1" = "-h" ]; then
cat << EOM
html-report -d <dir> [-S]
 -S show only official releases
 -d output directory
 -D support database
 -E include embargoed
EOM
    exit 0
fi

embargoed="EMBARGOED"
support_db=
outdir=
table_args=
suffix=
pythonver=
ubuntu_table_exe="./scripts/ubuntu-table"

if [ -n "$UCT_REVIEWED" ]; then
    ubuntu_table_exe="$UCT_REVIEWED/scripts/ubuntu-table"
fi

while getopts "hSEd:D:T:u:" opt
do
    case "$opt" in
        d) outdir="$OPTARG";;
        D) support_db="$OPTARG";;
        S) table_args="$table_args -S"
           suffix="-released"
           ;;
        T) table_args="$table_args $OPTARG";;
        u) ubuntu_table_exe="$OPTARG";;
        E) embargoed="THISISNOTTHEEMBARGOEDYOUARELOOKINGFOR";;
        h) help ; exit 0;;
        ?) help;;
    esac
done
shift $(($OPTIND - 1))


# setup the output directory
mkdir "$outdir" 2>/dev/null || true
if [ ! -d "$outdir" ]; then
    echo "ERROR: '$outdir' does not exist"
    exit 1
fi

if [ -n "$UCT_REVIEWED" ] && [ -z "$UCT" ]; then
    echo "ERROR: must set UCT when using UCT_REVIEWED"
    exit 1
fi

# setup the temp directory
tmpdir=`mktemp -d`
trap "rm -rf ${tmpdir}" EXIT

header() {
    outfile="$1"
    show="$2"
    main_active=""
    universe_active=""
    partner_active=""

    if [ "$show" = "main" ]; then
        main_active="active ";
    elif [ "$show" = "universe" ]; then
        universe_active="active ";
    elif [ "$show" = "partner" ]; then
        partner_active="active ";
    fi

    cat > "$outfile" <<EOM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-96529618-15"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-96529618-15');
</script>

<title>Ubuntu CVE Tracker</title>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Canonical Ltd, Kees Cook and Jamie Strandboge" />
<meta name="description" content="Ubuntu CVE Tracker" />
<meta name="copyright" content="Canonical Ltd" />

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="css/starter-template.css">
<link rel="stylesheet" href="css/filter.css" type="text/css" />
<link rel="stylesheet" href="css/cve_tracker.css" type="text/css" />

</head>

<body>
<nav class="navbar navbar-expand navbar-dark bg-dark navbar-fixed-top cve-tracker-navbar">
    <a class="navbar-brand" href="https://launchpad.net/ubuntu-cve-tracker">Ubuntu CVE Tracker</a>
    <div id="cve-tracker-navbar" class="collapse navbar-collapse">
      <ul class="navbar-nav">
        <li class="nav-item"><a class="nav-link" href=".">Home</a></li>
        <li class="nav-item"><a class="${main_active}nav-link" href="main.html">Main</a></li>
        <li class="nav-item"><a class="${universe_active}nav-link" href="universe.html">Universe</a></li>
        <li class="nav-item"><a class="${partner_active}nav-link" href="partner.html">Partner</a></li>
      </ul>
    </div><!--/.nav-collapse -->
</nav>
<div class="container-fluid" id="container">
<div class="starter-template">
<div class="card" id="body-card">
<h3 class="card-header text-center">Ubuntu ${show^} CVEs</h3>
<div class="card-body">
EOM
}

introduction() {
    outfile="$1"
    suffix="$2"
    cat >> "$outfile" <<EOM
<h3 class="text-left">Introduction</h3>
<p class="intro text-left">Ubuntu tracks its security vulnerabilities via the <a
href="https://launchpad.net/ubuntu-cve-tracker">Ubuntu CVE Tracker</a>. 
This report is divided into the following sections:</p>
<ul class="style-none text-left">
  <li><a href="main${suffix}.html">Main</a> (supported by Canonical Ltd)</li>
  <li><a href="universe${suffix}.html">Universe</a> (supported by the Ubuntu community)</li>
  <li><a href="partner${suffix}.html">Partner</a> (supported by upstream vendor)</li>
</ul>

<p class="text-left">See <a href="priority.html">Priority Color Key</a> for information about the significance of the colors on this page.</p>

<div id="filter" class="container.fluid text-left">
    <h3>Filters</h3>
    <div class="row">
        <div class="col-md-2">
            <select id="field-selector" class="form-control"></select>
        </div>
        <div class="col-md-2">
            <div id="filter-criteria">
            </div>
        </div>
        <div class="col-md-8"></div>
    <button type="button" class="and_button" style="display: none">AND</button>
    <button type="button" class="or_button" style="display: none">OR</button>
    </div>
    <div class="row">
        <div class="col" id="filter-button-div">
            <button class="btn btn-secondary" type="button" id="filter-button">Filter</button>
            <button class="btn btn-secondary" type="button" id="clear-filter-button">Clear Filter</button>
        </div>
    </div>
</div>
EOM
}

footer() {
    outfile="$1"
    NOW=$(date -u +"%Y-%m-%d %R %Z")
    COMMIT=$(git rev-parse HEAD)
    cat >> "$outfile" <<EOM
<p class='note'><a href="https://code.launchpad.net/~ubuntu-security/ubuntu-cve-tracker/master">Updated</a>: ${NOW} (commit <a href="http://git.launchpad.net/~ubuntu-security/ubuntu-cve-tracker/commit/?id=${COMMIT}">${COMMIT}</a>)</p>
</div>
<div id="footer">
EOM
    echo "&copy; Canonical Ltd. 2007-`date +%Y`" >> "$outfile"
    cat >> "$outfile" <<EOM
</div><!-- footer -->
</div><!-- card-body -->
</div><!-- card -->
</div><!-- starter-template -->
</div><!-- container -->
 <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="./js/filter.js"></script>
</body>
</html>
EOM

}

OUTPUT=$($ubuntu_table_exe --html --supported --no-retired $table_args)
#for show in main universe partner index
for show in main universe partner
do
    outfile="${tmpdir}/${show}${suffix}.html"
    header "$outfile" "$show"
    introduction "$outfile" "$suffix"

    if [ "$show" = "main" ]; then
        echo "<h3 class=\"text-center\">Main</h3>" >> "$outfile"
        # all this sed work strips out the last column
        echo "$OUTPUT" | egrep '(<table id="cves".*>|</table>|<thead.*>|</thead>|<tbody>|<tbody>|<th>|SUPPORTED)' | egrep -v "$embargoed" | sed -r 's#<td>[[:space:]]+(<p>[[:space:]]*[a-zA-Z0-9\-]*[[:space:]]*</p>[[:space:]]+)+</td>[[:space:]]+</tr>$#</tr>#' | sed -r 's#<th>Notes</th></tr>$#</tr>#' >> "$outfile"
        echo "<p class='note text-right'>* supported by Canonical Ltd</p>" >> "$outfile"
    elif [ "$show" = "universe" ]; then
        echo "<h3 class=\"text-center\">Universe</h3>" >> "$outfile"
        echo "$OUTPUT" | egrep '(<table id="cves".*>|</table>|<thead.*>|</thead>|<tbody>|<tbody>|<th>|UNIVERSE)' | egrep -v 'PARTNER' | egrep -v "$embargoed" | sed -r 's#<td>[[:space:]]+(<p>[[:space:]]*[a-zA-Z0-9\-]*[[:space:]]*</p>[[:space:]]+)+</td>[[:space:]]+</tr>$#</tr>#' | sed -r 's#<th>Notes</th></tr>$#</tr>#' >> "$outfile"
        echo "<p class='note text-right'>* supported by Canonical Ltd</p>" >> "$outfile"
    elif [ "$show" = "partner" ]; then
        echo "<h3 class=\"text-center\">Partner</h3>" >> "$outfile"
        echo "$OUTPUT" | egrep '(<table id="cves".*>|</table>|<thead.*>|</thead>|<tbody>|<tbody>|<th>|PARTNER)' | egrep -v "$embargoed"| sed -r 's#<td>[[:space:]]+(<p>[[:space:]]*[a-zA-Z0-9\-]*[[:space:]]*</p>[[:space:]]+)+</td>[[:space:]]+</tr>$#</tr>#' | sed -r 's#<th>Notes</th></tr>$#</tr>#' >> "$outfile"
    fi

    footer "$outfile"
done

err=
if [ -n "$support_db" ]; then
    if [ ! -f "$support_db" ]; then
        echo "Skipping flavors generation"
        err="yes"
    fi

    flavout="${tmpdir}/flavors.html"
    header "$flavout"
    echo "<ul>" >> "$flavout"

    for f in edubuntu kubuntu lubuntu mythbuntu ubuntu-budgie ubuntu-mate ubuntu-gnome ubuntustudio xubuntu ubuntukylin
    do
        outfile="${tmpdir}/${f}${suffix}.html"
        header "$outfile"
        echo '<p><a href="priority.html">Priority Color Key</a></p>' >> "$outfile"
        echo "<h3 id='$f'>CVEs affecting $f only</h3>" >> "$outfile"
        OUTPUT=$($ubuntu_table_exe --html --supported --no-retired $table_args --only-flavor --flavor="$f" --support-db="$support_db")
        echo "$OUTPUT" | egrep '(<table>|</table>|<th>|<tr)' | egrep -v "$embargoed" | sed -r 's#<td>[[:space:]]+<p>[[:space:]]*[a-zA-Z0-9\-]*[[:space:]]*</p>[[:space:]]+</td>[[:space:]]+</tr>$#</tr>#' | sed -r 's#<th>Notes</th></tr>$#</tr>#' >> "$outfile"
        footer "$outfile"

        outfile="${tmpdir}/${f}${suffix}-all.html"
        header "$outfile"
        echo '<p><a href="priority.html">Priority Color Key</a></p>' >> "$outfile"
        echo "<h3 id='$f'>All CVEs affecting $f</h3>" >> "$outfile"
        OUTPUT=$($ubuntu_table_exe --html --supported --no-retired $table_args --flavor="$f" --support-db="$support_db")
        echo "$OUTPUT" | egrep '(<table>|</table>|<th>|<tr)' | egrep -v "$embargoed" | sed -r 's#<td>[[:space:]]+<p>[[:space:]]*[a-zA-Z0-9\-]*[[:space:]]*</p>[[:space:]]+</td>[[:space:]]+</tr>$#</tr>#' | sed -r 's#<th>Notes</th></tr>$#</tr>#' >> "$outfile"

        footer "$outfile"

        echo "  <li>Open <a href='$f.html'>CVEs in $f</a> (<a href='$f-all.html'>all CVEs affecting $f</a>)</li>" >> "$flavout"
    done
    echo "</ul>" >> "$flavout"
    footer "$flavout"
fi

mv -f ${tmpdir}/* ${outdir}

if [ "$err" = "yes" ]; then
    exit 1
fi
