#!/usr/bin/env bash

# Enable strict mode
set -euo pipefail
IFS=$'\n\t'

if [ $# -ne 1 ]; then
	echo "Usage: ./prepare-release <next_version>"
	exit 1
fi

next_version=$1
current_version="$(git tag -l "*.*.*" | sort | tail -n 1)"

if [[ -z "${current_version}" ]]; then
	echo "Failed to get latest version. Aborting"
	exit 2
fi

echo "Current version: ${current_version}"
echo "Next version:    ${next_version}"
read -p "Continue? [y/n] " -n 1 -r
echo

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
	exit 3
fi

echo

bin_directory="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
root_directory="$(cd "${bin_directory}/.." || exit 4 && pwd)"

# Update version
echo "Bumping version..."

files=(
	"Cargo.toml"
	"README.md"
)

for file in "${files[@]}"; do
	vim -c "%s/${current_version}/${next_version}/g" -c "wq" "${root_directory}/${file}"
done

# Updating changelog
echo "Updating changelog..."
vim "${root_directory}/CHANGELOG.md"

# Commit changes
echo "Committing changes..."
git checkout -b "release-${next_version}" >/dev/null 2>&1
git add . >/dev/null 2>&1
git commit -m "Release ${next_version}" >/dev/null 2>&1

echo
echo "Release of version ${next_version} prepared. Push the branch, open a pull"
echo "request, and wait for review. Once merged, create a new release on GitHub."
echo
