#!/usr/bin/env bash

set -e

function print_usage() {
  cat <<EOF
$(basename "$0") VERSION

This script announces the release of a new version of Alda on Slack.

The announcement includes the changelog that was uploaded along with the release
executables.

EOF
}

release_version="$1"

if [[ -z "$release_version" ]]; then
  print_usage
  exit 1
fi

if [[ -z "$ALDA_SLACK_WEBHOOK_URL" ]]; then
  echo "ALDA_SLACK_WEBHOOK_URL must be set."
  exit 1
fi

for cmd in jo curl; do
  if ! command -v "$cmd" > /dev/null; then
    echo "This script requires \`$cmd\` to be installed."
    exit 1
  fi
done

anchor="$(grep "$release_version" "$(dirname "$0")/../CHANGELOG.md" \
  | head -n1 \
  | sed 's/^#\+ //' \
  | tr -d '.()' \
  | tr ' ' '-')" \

if [[ -z "$anchor" ]]; then
  echo "Release version '$release_version' not found in CHANGELOG.md"
  exit 1
fi

release_notes_url="https://github.com/alda-lang/alda/blob/master/CHANGELOG.md#$anchor"

################################################################################
# Wait until release is available via the Alda API
################################################################################

alda_api_url="https://api.alda.io/release/$release_version"

while true; do
  echo "Waiting for the release to become available via the Alda API..."

  if curl -s --fail "$alda_api_url" >/dev/null; then
    echo "Release available."
    break
  fi

  sleep 10
done

################################################################################
# Announce release on Slack
################################################################################

release_now_available="*Alda version $release_version is now available!* Here are the <$release_notes_url|release notes>."

instructions="$(cat <<EOF
_To get the latest version of Alda, go to https://alda.io/install or run \`alda update\`._
EOF
)"

slack_channel="general"

curl \
  -X POST \
  -H Content-Type:application/json \
  "$ALDA_SLACK_WEBHOOK_URL" \
  --data "$(jo \
              channel="$slack_channel" \
              icon_emoji="alda" \
              username="Release announcement" \
              blocks="$(jo -a \
                          "$(jo \
                               type="section" \
                               text="$(jo \
                                         type="mrkdwn" \
                                         text="$release_now_available")")" \
                          "$(jo type="divider")" \
                          "$(jo \
                               type="section" \
                               text="$(jo \
                                         type="mrkdwn" \
                                         text="$instructions")")")")"
