#!/bin/bash

set -euo pipefail

if [[ -z "${1:-}" || "$1" == '--help' || "$1" == '-h' ]]; then
  echo "Usage: $0 RELEASE_VERSION"
  exit 1
fi

release_version="$1"
RELEASE_NAME="v${release_version}"

#####################
#  COVERAGE REPORT  #
#####################

# The report would have been generate when the docker image is built.
COVERAGE_LOCAL_DIR="coverage"
COVERAGE_S3_BUCKET="s3://zoox-web/planner-metrics/pmav/coverage/${RELEASE_NAME}/"
COVERAGE_URL="http://planner-metrics.web.zooxlabs.com/pmav/coverage/${RELEASE_NAME}/index.html"

# This correctly assumes that the right AWS creds are set.
# The terraform commands in the prior step wouldn't have worked otherwise.
echo -e "\nUploading coverage report ..."
aws s3 cp --quiet --recursive $COVERAGE_LOCAL_DIR $COVERAGE_S3_BUCKET

echo -e "\nUpload successful!"
echo "Coverage Report: $COVERAGE_URL"

#######################
#  LIGHTHOUSE REPORT  #
#######################

# Lighthouse scores depend on a number of factors. They could be different
# every time you generate it from the same commit it also depends on the
# client network bandwidth. We can store them anyway for accounting. The
# scores also vary between pages. We are only considering PMAV's homepage
# here. We have been investigating the results since quite some time now
# and know all the things it takes to get a perfect score but note that
# a perfect lighthouse score isn't the only indicator of (perceived)
# performance of an app. Lighthouse scores can be easily hacked.

TEMP_LH_FILE="lighthouse.html"
LH_FILE="${RELEASE_NAME}.html"
LH_S3_BUCKET="s3://zoox-web/planner-metrics/pmav/performance/lighthouse/${LH_FILE}"
LH_REPORT_URL="http://planner-metrics.web.zooxlabs.com/pmav/performance/lighthouse/${LH_FILE}"

echo -e "\nGenerating lighthouse report ..."
npx lighthouse \
    https://pmav.zooxlabs.com \
    --quiet \
    --preset=desktop \
    --chrome-flags="--no-sandbox --headless --disable-gpu" \
    --only-categories "accessibility,best-practices,performance,seo" \
    --output-path $TEMP_LH_FILE

echo -e "\nUploading lighthouse report ..."
aws s3 cp --quiet $TEMP_LH_FILE $LH_S3_BUCKET

# Remove local copy
rm $TEMP_LH_FILE

echo -e "\nUpload successful!"
echo "Lighthouse Report: $LH_REPORT_URL"
