#!/usr/bin/env bash

set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

die() {
  echo "Error:" "$@" >&2
  exit 1
}

[[ "${1-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] \
  || die "usage is scripts/bump-version <version>"

VERSION="$1"

[[ -z "$(git status --porcelain)" ]] \
  || die "repository is not in a clean state"

# Dancing around macOS sed

if [[ -d "/opt/homebrew/opt/gnu-sed/libexec/gnubin" ]]; then
  export PATH="/opt/homebrew/opt/gnu-sed/libexec/gnubin:$PATH"
fi

sed --version | grep -q 'sed (GNU sed)' \
  || die "non-GNU sed"

cargo test --locked --all-features \
  || die "tests failed; fix your stuff"

cargo check --locked --all-features \
  || die "cargo check failed; fix your stuff"

cargo fmt --all -- --check \
  || die "rustfmt failed; clean up your stuff"

cargo clippy --all --all-features \
  || die "clippy failed; clean up your stuff"

cargo build --locked --all-features \
  || die "cargo build failed; fix your stuff"

cargo audit --deny warnings --deny unmaintained --deny unsound --deny yanked \
  || die "audit failed; fix libs"

# Bump Cargo.{toml,lock}
sed -i -Ee 's/^version = "[0-9]+\.[0-9]+\.[0-9]+"$/version = "'"$VERSION"'"/' Cargo.toml \
  && git status --porcelain | grep -q '^ M Cargo.toml$' \
  && cargo check \
  || die "failed to update Cargo.toml"

# Commit and release tag
git add Cargo.toml Cargo.lock
git commit -m "Bump version to ${VERSION}"
git tag -a -m "Release ${VERSION}" "v${VERSION}"
git show HEAD
