#!/usr/bin/env bash

# This script downloads the build artifacts along with the signatures, verifies the signatures and
# creates a GitHub release. This should be run after `4-update-and-publish-metadata`. To skip
# creating a draft release, add the --final flag.

set -eu

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

function usage {
    echo "Usage: $0 [--final] [-h|--help]"
    echo "  --final Publish GitHub release instead of creating a draft"
    exit 0
}

DRAFT="true"
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --final) DRAFT="false";;
        --draft) DRAFT="true";;
        -h|--help) usage ;;
    esac
    shift
done

REPO_ROOT=../../../
PRODUCT_VERSION_PATH=$REPO_ROOT/dist-assets/desktop-product-version.txt
PRODUCT_VERSION=$(cat $PRODUCT_VERSION_PATH)
CHANGELOG_PATH=$REPO_ROOT/CHANGELOG.md

$REPO_ROOT/scripts/utils/gh-ready-check
$REPO_ROOT/scripts/utils/commit-verification
"$SCRIPT_DIR/verify-version-is-release"

# shellcheck source=desktop/scripts/release/release-config.sh
source "$SCRIPT_DIR/release-config.sh"
source $REPO_ROOT/scripts/utils/log

rm -rf "$ARTIFACT_DIR" && mkdir -p "$ARTIFACT_DIR" || exit 1

function publish_release {
    log_header "Downloading changelog"

    changelog_end_version_pattern="20[0-9]\{2\}\.[0-9]\{1,2\}"
    if [[ $PRODUCT_VERSION == *-beta* ]]; then
        changelog_end_version_pattern=".*"
    fi

    changelog_extract=$(sed -n "/^## \[$PRODUCT_VERSION\]/,/^## \[$changelog_end_version_pattern\]/p" "$CHANGELOG_PATH")

    changelog=$(echo "$changelog_extract" | sed '$d' | \
        awk 'NF { last = last ? last ORS $0 : $0 } END { print last }')

    release_flags=(
      --repo "git@github.com:mullvad/mullvadvpn-app"
      --verify-tag
      --notes-file -
      --title "$PRODUCT_VERSION"
    )

    if [[ "$DRAFT" == "true" ]]; then
      release_flags+=(--draft)
    fi

    previous_release=$(echo "$changelog_extract" | tail -1 | grep -oP '## \[\K[^\]]+')

    body="This release is for desktop only."
    if [[ $PRODUCT_VERSION == *-beta* ]]; then
        body+="\n\nHere is a list of all changes since last release [$previous_release](https://github.com/mullvad/mullvadvpn-app/releases/tag/$previous_release):"
        release_flags+=(--prerelease)
    else
        body+="\n\nHere is a list of all changes since last stable release [$previous_release](https://github.com/mullvad/mullvadvpn-app/releases/tag/$previous_release):"
        release_flags+=(--latest)
    fi

    version_count=$(echo "$changelog" | grep -c "^## ")
    if [ "$version_count" -eq 1 ]; then
        changelog=$(echo "$changelog" | tail -n +2)
    fi

    body+="\n$changelog"

    read -rp "The suggested changelog will be opened in an editor, please finalize and save it before exiting. Press enter to open changelog..."

    tmp_changelog_file=$(mktemp)
    {
      printf "%b" "$body"
      printf "%b" "\n\n<!--\nThe following artifacts will be included:\n"
      # shellcheck disable=SC2012
      ls -lh "$ARTIFACT_DIR" | tail -n +2 | awk '{print $9,"( Size:",$5,")"}'
      echo "-->"
    } > "$tmp_changelog_file"

    "${EDITOR:-"vim"}" "$tmp_changelog_file"

    log_header "Creating GitHub release"
    # shellcheck disable=SC2046
    gh release create "${release_flags[@]}" "$PRODUCT_VERSION" $(printf "%s " "$ARTIFACT_DIR"/*) < "$tmp_changelog_file"

    if [[ "$DRAFT" == "true" ]]; then
      log_success "\nThe above URL contains the text \"untagged\", but don't worry it is tagged properly and everything will look correct once it's published."
    fi
}

function remove_release_artifacts {
    log_header "Cleaning up $ARTIFACT_DIR"
    rm -r "$ARTIFACT_DIR"
}

./download-release-artifacts "$PRODUCT_VERSION" "$ARTIFACT_DIR"
publish_release
remove_release_artifacts
