#!/usr/bin/env bash

# This script creates and pushes a signed release tag. This should be run after `1-prepare-release`.

set -eu

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

REPO_ROOT=../../../
PRODUCT_VERSION_PATH=$REPO_ROOT/dist-assets/desktop-product-version.txt
PRODUCT_VERSION=$(cat $PRODUCT_VERSION_PATH)
BASE_URL="https://releases.mullvad.net/desktop/releases/$PRODUCT_VERSION"

$REPO_ROOT/scripts/utils/commit-verification

source $REPO_ROOT/scripts/utils/print-and-run
source $REPO_ROOT/scripts/utils/log

WAIT="false"

for argument in "$@"; do
    case "$argument" in
        --wait)
          WAIT="true"
          ;;
        *)
            log_error "Unknown option \"$argument\""
            exit 1
            ;;
    esac
done

function push_tag {
    product_version=$(echo -n "$PRODUCT_VERSION")
    echo "Tagging current git commit with release tag $product_version..."
    print_and_run git tag -s "$product_version" -m "$product_version"
    git push
    print_and_run git push origin "$product_version"
    log_success "\nTag pushed!"
}

function wait_for_build {
  log_header "Checking availability of release artifacts"
  for ext in .exe _arm64.exe _x64.exe _amd64.deb _arm64.deb _x86_64.rpm _aarch64.rpm .pkg _x86_64.pkg _arm64.pkg; do
    pkg_filename="MullvadVPN-${PRODUCT_VERSION}${ext}"
    url="$BASE_URL/$pkg_filename"

    log_info "Waiting for $ext"
    while ! curl --head --fail --silent "$url" > /dev/null; do
      sleep 30s
    done
  done

  log_success "\nAll artifacts are now available"
}

push_tag

log_success "Follow build progress here: $BASE_URL"

if [[ "$WAIT" == "true" ]]; then
  wait_for_build
fi
