#!/bin/sh
set -eu
. "$(git rev-parse --show-toplevel)/ci/msrv.sh"

step() {
    >&2 echo
    >&2 echo ">>> $*"
}

if ! command -v cargo > /dev/null 2>&1; then
    curl -o ~/rustup-init https://static.rust-lang.org/rustup/dist/x86_64-unknown-linux-gnu/rustup-init
    chmod +x ~/rustup-init
    ~/rustup-init -y --default-toolchain $msrv
    . ~/.cargo/env
fi

step 'create release on codeberg.org'
# we create annotated tags in ci/start-release.sh, but actions/checkout fetches the tag as a
# lightweight tag, even with `fetch-tags: true` and/or `fetch-depth: 0`, so we must use `--tags`.
tag_name=$(git describe --exact-match --tags)
target_commitish=$(git rev-parse HEAD)
# --json ≈ --header 'Content-Type: application/json' --data-binary
jq -en \
	--arg tag_name "$tag_name" \
	--arg target_commitish "$target_commitish" \
	'{$tag_name,$target_commitish,draft:true}' \
| curl -fsSH "Authorization: Bearer $FORGEJO_TOKEN" \
	--header 'Content-Type: application/json' --data-binary @- \
	"https://codeberg.org/api/v1/repos/$FORGEJO_REPOSITORY/releases"

step 'publish package to crates.io'
package_name=$(git describe --exact-match --tags | egrep -o '^[^-]+(-[^0-9-]+)*')
( set -x; cargo +$msrv publish -p "$package_name" )
