#!/usr/bin/env bash
set -eu

this_dir=${BASH_SOURCE[0]%/*}

# shellcheck source=tools/lib/ensure-coreutils.sh
. "${this_dir}"/lib/ensure-coreutils.sh

usage () {
    cat <<EOF >&2
usage: bump-version

Increments the version number in our pubspec and changelog.
EOF
    exit 2
}

shift && usage;

major_version=30
minor_version=0
pub_version_regexp="${major_version}\.${minor_version}\.(\d+)\+\1"

date="$(date --iso)"

old_version_int="$(perl -lne '
print $1 if (/^version: '"${pub_version_regexp}"'$/);
' pubspec.yaml)"
if [ -z "${old_version_int}" ]; then
    echo >&2 "error: failed to parse current version in pubspec.yaml"
    exit 1
fi

version_int=$(( old_version_int + 1 ))
version_name="${major_version}.${minor_version}.${version_int}"
pub_version="${version_name}+${version_int}"
tag_name=v"${version_name}"

had_uncommitted=
if ! git diff-index --quiet HEAD; then
    had_uncommitted=1
fi

perl -i -0pe '
s<^version: \K'"${pub_version_regexp}"'$>
 <'"${pub_version}"'>m;
' pubspec.yaml

perl -i -0pe '
s/^\#\#\ Unreleased\n\K
/

## '"${version_name}"' ('"${date}"')
/xms
' docs/changelog.md

msg="version: Bump version to $version_name"

if [ -n "$had_uncommitted" ]; then
    {
        echo "There were uncommitted changes.  To commit:"
        echo "  git commit -am ${msg@Q}"
        # NB if tempted to use the ${...@Q} feature: it's new in bash 4.4,
        # released 2016-09, found in stretch and bionic but not xenial.
        echo
        echo "Then tag the commit:"
        echo "  git tag ${tag_name}"
        echo "inspect the result, and push:"
        echo "  git push origin main ${tag_name}"
    } >&2
    exit 1
fi

git commit -am "$msg"

git tag "${tag_name}"

{
    echo
    echo "Committed and tagged."
    echo "Inspect the result, then push; for example:"
    echo "  git push origin main ${tag_name}"
} >&2
