#!/bin/bash
set -o errexit \
    -o nounset \
    -o pipefail

REGEX='^dist/influxdb2-client-([[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+)(.*)'

for target in dist/*
do
  # `dist` contains more than just the packages. This will match
  # only the artifacts with a "package" filename.
  if [[ "${target}" =~ ${REGEX} ]]
  then
    mv -v "${target}" "dist/influxdb2-client-latest${BASH_REMATCH[2]}"

    # After renaming the artifact to the "lastest" version, append the
    # artifact to the `invalidations` file. Since `dl.influxdata.com`
    # contains many 100GBs, this should only invalidate artifacts
    # that have changed.
    printf '/influxdb/releases/influxdb2-client-latest%s\n' "${BASH_REMATCH[2]}" >>invalidations
  fi
done

aws s3 sync dist 's3://dl.influxdata.com/influxdb/releases/'

aws cloudfront create-invalidation --distribution-id "${AWS_DISTRIBUTION_ID}" --paths $(<invalidations)
