#!/bin/bash
set -euo pipefail
shopt -s extglob

devel="$(dirname "$0")"

main() {
    local version="${1:?version is required}"
    local commit pre_release
    shift
    local -a assets=("$@")

    if [[ ${#assets[@]} -eq 0 ]]; then
        echo "ERROR: no assets provided" >&2
        exit 1
    fi

    # Asserts that $version is an actual tag, not a branch name or other ref.
    git rev-parse --verify "$version^{tag}" >/dev/null

    # Translate from tag into commit for `gh release create --target`.
    commit="$(git rev-parse --verify "$version^{commit}")"

    if is-pre-release "$version"; then
        pre_release=1
    fi

    gh release create \
        "$version" \
        --repo "${GITHUB_REPOSITORY:-nextstrain/augur}" \
        --title "$version" \
        --target "$commit" \
        ${pre_release:+--prerelease} \
        --notes-file <(preamble; "$devel"/changes "$version") \
        "${assets[@]}"
}

is-pre-release() {
    # See https://peps.python.org/pep-0440/
    local version="$1"
    case "$version" in
        *@(a|b|rc|c)+([0-9])*)  # alpha, beta, release candidate (PEP 440 pre-releases)
            return 0;;
        *.dev+([0-9])*)         # dev release
            return 0;;
        *+*)                    # local version
            return 0;;
        *)
            return 1;;
    esac
}

preamble() {
    cat <<~~

_These release notes are automatically extracted from the full [changelog][]._

[changelog]: https://github.com/nextstrain/augur/blob/-/CHANGES.md#readme

~~
}

main "$@"
