#!/usr/bin/env bash

# Configure the script to exit when a command fails.
set -e

: ${SCRIPTS_ROOT:="$(dirname $0)"}
export SCRIPTS_ROOT
source "${SCRIPTS_ROOT:?}"/util.sh

# ===== CONSTANTS =====

: ${SELF:="$(basename $0)"}

: ${REPOSITORY_ROOT:="${SCRIPTS_ROOT:?}"/..}
VERSION_FILE="${REPOSITORY_ROOT:?}"/VERSION
CHANGELOG_FILE="${REPOSITORY_ROOT:?}"/CHANGELOG.md

VERSION="$(cat "${VERSION_FILE:?}")"

# ===== HELPER FUNCTIONS =====

description() {
	cat <<EOF
${Bold}Prepares changelog entries for the next release.${Bold_Off}

This script is not a replacement for writing changelog entries manually, it’s
only there to speed it up. It won’t work if you have already started writing
unreleased changelog entries.
EOF
}

usage() {
	cat <<EOF
$(format_title 'Usage:')
  $(format_command "${SELF:?}")

$(format_title 'Options:')
  $(format_subtitle 'Miscellaneous options:')
    $(format_flag --help)
      Explains what the command does and how to use it.
EOF
}

help() {
	printf "$(description)\n"
	echo ''
	printf "$(usage)\n"
	exit 0
}

to-tag() {
	echo "v${1:?"Must pass a version number"}"
}

git-log() {
	git --no-pager log --reverse --no-merges \
		--format="${1:?"Format expected"}" --date=short --color \
		"$(to-tag "${VERSION:?}")"..HEAD
}

# ===== ARGUMENT PARSING =====

for arg in "$@"; do
	case $arg in
		--help) help ;;
		*) error "Unknown argument: $(format_code $arg)."; info "$(usage)"; die ;;
	esac
done

# ===== MAIN LOGIC =====

if ! grep -zq '...HEAD\n\n## \['"${VERSION:?}"'\]' "${CHANGELOG_FILE:?}"; then
	error "Cannot prepare changelog entries when some already exist."
	info "For your information, commits since last release ($(format_code "$(to-tag "${VERSION:?}")")) are:"
	git-log '- %s (in `%C(auto)%h`)'
	die
fi

edo cat <<EOF > temp
$(git-log '- %s (in `%h`)')

### Removed

- TODO

### Changed

- TODO

### Added

- TODO

### Fixed

- TODO

EOF

# Source: <https://unix.stackexchange.com/a/193498/632020>.
edo ed -s "${CHANGELOG_FILE:?}" <<EOF
/## \[${VERSION:?}\]/-r temp
w
q
EOF

rm temp

success Successfully prepared next changelog entries.

warn '========================================================================'
warn "As stated in $(format_hyperlink 'Keep a Changelog' 'https://keepachangelog.com/en/1.1.0/'), changelogs are meant for humans. This"
warn 'script simplified your job of writing it by inserting all commits since'
warn "last release ($(format_code "$(to-tag "${VERSION:?}")")) but you still have to split it into Removed/"
warn 'Changed/Added/Fixed and make it human-readable. Some commits should'
warn 'probably be removed, and others might need to be squashed into a single'
warn 'changelog entry.'
warn '========================================================================'
