#!/usr/bin/env bash

# run by the release-prepare.yml github action workflow
# * start from a release/A.B.C branch
# * create a changelog file with only this one version's entry
#   * we'll store it as a github artifact and use it later
#     to create a github release.
# * update and commit CHANGELOG.md

[ -n "$DEBUG" ] && set -x
set -euo pipefail

source "$(dirname "${BASH_SOURCE[0]}")/check-working-dir"
# note also that changelog-build is not `git worktree` friendly.
# https://github.com/hashicorp/go-changelog/pull/49
# -> https://github.com/go-git/go-git/issues/1812

echo 'Checking variables'
  SOURCE_BRANCH="${SOURCE_BRANCH:-$(git branch --show-current)}"
  # vars displayed this way for easier troubleshooting
  cat <<VARS
\`\`\`
# required:
export NEW_VERSION='${NEW_VERSION?is required}'
export LAST_RELEASE='${LAST_RELEASE?is required}'
# derived:
export SOURCE_BRANCH='$SOURCE_BRANCH'

$0
\`\`\`

VARS

echo 'Ensuring source branch'
  git fetch origin "$SOURCE_BRANCH"
  git switch "$SOURCE_BRANCH"
  git pull origin "$SOURCE_BRANCH"
echo

cl_file="$(mktemp -t changelog-XXXXX-$NEW_VERSION.md)"

echo "Generating the changelog from v$LAST_RELEASE to HEAD ($(git rev-parse HEAD))"
  # changelog-build does checkouts, so hold on to current branch
  _start_branch="$(git branch --show-current)"
  changelog-build \
    -last-release "v$LAST_RELEASE" \
    -this-release HEAD \
    -entries-dir .changelog \
    -changelog-template .changelog/changelog.tmpl \
    -note-template .changelog/note.tmpl \
    -local-fs > "$cl_file"
  # back to where we came from
  git switch "$_start_branch"
  
  lines="$(wc -l "$cl_file" | awk '{print$1}')"
  if [ "$lines" -eq 0 ]; then
    echo "::error::Generated changelog is empty"
    exit 1
  fi
echo

echo "Updating CHANGELOG.md"
  {
    echo "## ${NEW_VERSION//+ent/ Enterprise} ($(date '+%B %d, %Y'))"
    cat "$cl_file"
    echo
    cat CHANGELOG.md
  } > "changelog.tmp.md"
  mv "changelog.tmp.md" CHANGELOG.md
echo

echo "Committing changes"
  git add CHANGELOG.md
  git status
  git diff --cached --color=always | /bin/cat
  git commit -m "release: Update changelog for $NEW_VERSION"
echo

echo "file=$cl_file" >> "${GITHUB_OUTPUT:-/dev/stderr}"
