#!/bin/bash
# Script: upload debug information and source bundle to Sentry when deploying the new version.
#
# Positional arguments:
#   $1: Release version (commit SHA)
#
# Required environment variables:
#   SENTRY_AUTH_TOKEN: Sentry auth token (https://sentry.io/settings/account/api/auth-tokens/)
#   SENTRY_ORG: Organization slug
#   SENTRY_PROJECT: Project slug
set -eu

REVISION="${1:-}"
GITHUB_PROJECT="getsentry/relay"
DOCKER_IMAGE="us.gcr.io/sentryio/relay:${REVISION}"

if [ -z "${REVISION}" ]; then
  echo 'No version specified' && exit 1
fi

if [ -z "${SENTRY_AUTH_TOKEN:-}" ]; then
  echo 'No Sentry auth token found' && exit 1
fi

if [ -z "${SENTRY_ORG:-}" ] || [ -z "${SENTRY_PROJECT:-}" ]; then
  echo 'No SENTRY_ORG or SENTRY_PROJECT provided' && exit 1
fi

echo 'Pulling debug information from relay image...'
docker pull "${DOCKER_IMAGE}"

docker run --rm --entrypoint cat "${DOCKER_IMAGE}" /opt/relay-debug.zip > relay-debug.zip
docker run --rm --entrypoint cat "${DOCKER_IMAGE}" /opt/relay.src.zip > relay.src.zip
docker run --rm --entrypoint tar "${DOCKER_IMAGE}" -cf - /lib/x86_64-linux-gnu > libs.tar
tar xf libs.tar

echo 'Uploading debug information and source bundle...'
sentry-cli upload-dif ./relay-debug.zip ./relay.src.zip

echo 'Uploading system symbols...'
sentry-cli upload-dif lib/x86_64-linux-gnu

echo 'Obtaining version information...'
VERSION="$(docker run --rm "${DOCKER_IMAGE}" --version | cut -d' ' -f2)"
RELEASE="relay@${VERSION}+${REVISION}"  # match RELEASE in relay_log::setup

echo "Creating a new release and deploy for ${RELEASE} in Sentry..."
sentry-cli releases new "${RELEASE}"
sentry-cli releases set-commits "${RELEASE}" --commit "${GITHUB_PROJECT}@${REVISION}"
sentry-cli releases deploys "${RELEASE}" new -e release
sentry-cli releases finalize "${RELEASE}"
echo 'Deploy created.'
