#!/usr/bin/env bash

set -euo pipefail

: "${COVERAGE_STAGE_DIR:?COVERAGE_STAGE_DIR is required}"
: "${COVERAGE_ARCHIVE_NAME:?COVERAGE_ARCHIVE_NAME is required}"
: "${COVERAGE_BUCKET:?COVERAGE_BUCKET is required}"
: "${COVERAGE_ARCHIVE_KEY:?COVERAGE_ARCHIVE_KEY is required}"
: "${COVERAGE_MANIFEST_NAME:?COVERAGE_MANIFEST_NAME is required}"
: "${COVERAGE_MANIFEST_KEY:?COVERAGE_MANIFEST_KEY is required}"
: "${MINIO_ENDPOINT:?MINIO_ENDPOINT is required}"

archive_local="${COVERAGE_STAGE_DIR}/${COVERAGE_ARCHIVE_NAME}"
manifest_local="${COVERAGE_STAGE_DIR}/${COVERAGE_MANIFEST_NAME}"
archive_remote="s3://${COVERAGE_BUCKET}/${COVERAGE_ARCHIVE_KEY}"
manifest_remote="s3://${COVERAGE_BUCKET}/${COVERAGE_MANIFEST_KEY}"

# Upload tarball first, then manifest. If manifest upload fails, remove the
# orphaned tarball so the bucket never contains a tarball without its manifest.
aws s3 cp \
    "${archive_local}" \
    "${archive_remote}" \
    --endpoint-url "${MINIO_ENDPOINT}" \
    --only-show-errors

if ! aws s3 cp \
    "${manifest_local}" \
    "${manifest_remote}" \
    --endpoint-url "${MINIO_ENDPOINT}" \
    --only-show-errors; then
    echo "Manifest upload failed; cleaning up orphaned tarball" >&2
    if ! aws s3 rm "${archive_remote}" \
        --endpoint-url "${MINIO_ENDPOINT}" \
        --only-show-errors; then
        echo "Failed to clean up orphaned tarball ${archive_remote}" >&2
    fi
    exit 1
fi
