#!/usr/bin/env bash
# semantic-release `prepareCmd` hook (see .releaserc.json).
#
# Invoked as: ./prepare.sh <lastRelease.version> <nextRelease.version> <nextRelease.type>
#
# semantic-release tags whatever commit this leaves behind, so bumping the
# crate version here is what keeps the tag, Cargo.toml and the crates.io
# publish (rust-publish, in the tag pipeline) in agreement.
#
# Runs in the semantic-release job, whose image is node:lts-slim - there is no
# cargo here, hence sed/awk instead of `cargo set-version`.
set -euo pipefail

next_version="$2"
old_version="$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml | head -1)"

if [ "$next_version" = "$old_version" ]; then
  echo "Cargo.toml is already at $next_version"
  exit 0
fi

sed -i -E "0,/^version = \"[^\"]*\"$/s//version = \"${next_version}\"/" Cargo.toml

# Cargo.lock records the crate's own version too. Rewrite it in place, anchored
# on the package name so dependency versions are untouched.
awk -v version="$next_version" '
  $0 == "name = \"move-diff\"" { in_move_diff = 1; print; next }
  in_move_diff && $0 ~ /^version = "/ { print "version = \"" version "\""; in_move_diff = 0; next }
  { print }
' Cargo.lock >Cargo.lock.tmp
mv Cargo.lock.tmp Cargo.lock

echo "bumped $old_version -> $next_version in Cargo.toml and Cargo.lock"