#!/usr/bin/env bash
# Wrapper around `git commit` that regenerates CHANGELOG.md via git-cliff
# and amends it into the same commit, keeping the changelog always in sync.
#
# Usage:  ./scripts/commit.sh [--tag <name>] [<git-commit-args>…]
#
# All arguments after the optional `--tag` are forwarded verbatim to
# `git commit`.  If the commit succeeds, git-cliff regenerates CHANGELOG.md
# and the result is folded into the commit.
#
# Use `--tag <name>` when the commit should be tagged before git-cliff runs
# (required for release commits so cliff sees the new version).  The tag is
# created between the commit and the changelog regeneration.
#
# Prerequisites:
#   - git-cliff installed (see mise.toml or cargo install git-cliff)

set -euo pipefail

TAG=""

if [[ "${1:-}" == "--tag" ]]; then
    TAG="$2"
    shift 2
fi

# Pass through to git commit.  If it fails (e.g. empty commit, aborted
# message editor) we bail before touching the changelog.
git commit "$@"

# If a tag was requested, create it now so git-cliff can find it.
if [[ -n "$TAG" ]]; then
    git tag "$TAG"
fi

# Regenerate changelog from the updated history.
git cliff -o CHANGELOG.md

# Fold the regenerated changelog into the commit we just made.
# Use -n to skip pre-commit hooks: the check-changelog-cliff hook would
# run against the *staged* changelog, which at this point is already in
# sync, but the hook's git-cliff invocation may disagree depending on
# where the tag pointer sits relative to HEAD.
git add CHANGELOG.md
git commit --amend --no-edit -n
