#!/bin/bash

# This script runs genhtml (part of lcov) on lcov artifacts generated by the
# code-coverage.sh script and uploads the result to a GCS bucket.

BUCKET="${BUCKET:-crl-codecover-public}"

set -euxo pipefail

publish() {
  PROFILE="$1"
  TITLE="$2"

  if [ ! -f "$PROFILE" ]; then
    echo "$PROFILE does not exist"
    exit 1
  fi

  DIR="$(date -r "$PROFILE" -u '+%Y-%m-%d %H:%MZ') $(git rev-parse --short=8 HEAD) - $TITLE"

  mkdir -p "artifacts/$DIR"
  # The filename shows up on the generated page, let's make it useful.
  cp "$PROFILE" "artifacts/$DIR.lcov"
  genhtml "artifacts/$DIR.lcov" -o "artifacts/$DIR"

  gsutil -m cp -Z -r "artifacts/$DIR" "gs://$BUCKET/pebble/$DIR"
}

publish "artifacts/profile-tests.lcov" "tests only"
publish "artifacts/profile-meta.lcov" "meta test only"
publish "artifacts/profile-tests-and-meta.lcov" "tests + meta"

# Regenerate index.html.
echo '<title>Pebble coverage</title><body><h2>Pebble coverage runs:</h2><ul>' > artifacts/index.html
gsutil ls "gs://$BUCKET/pebble" |
  sed "s#gs://$BUCKET/pebble/##" |
  sed 's#/$##' |
  grep -v index.html |
  sort -r |
  while read -r d; do
    echo "<li><a href=\"$d/index.html\">$d</a>" >> artifacts/index.html
  done

echo '</ul></body>' >> artifacts/index.html

gsutil cp artifacts/index.html "gs://$BUCKET/pebble/index.html"
gsutil setmeta -h "Cache-Control: public, max-age=300, no-transform" "gs://$BUCKET/pebble/index.html"
