#!/bin/bash -eu
#
# Close a release
#

function usage()
{
	cat <<EOF
Usage: $(basename "${0}") [-h]

Close a release, i.e., create a release commit.

Optional arguments:
  -h, --help  Show this help text and exit.
EOF
}

while [ ${#} -gt 0 ] ; do
	case "${1}" in
		-h|--help)
			usage
			exit
			;;
		*)
			echo "Invalid argument: ${1}" >&2
			exit 2
			;;
	esac
	shift
done

# Current upstream commit and version
. debian/upstream

# Current package release and version
release=$(dpkg-parsechangelog -SDistribution)
version=$(dpkg-parsechangelog -SVersion)

# New release version and and tag
if [ "${version%-*}" = "${VERSION}" ] ; then
	# Bump the upload number
	upload=$(echo "${version}" | grep -o '[0-9]*$')
	new_version=${version%${upload}}$((upload + 1))
else
	# New upstream version
	new_version="${VERSION}-0ubuntu1"
fi
new_tag="Ubuntu-${new_version}"

# Check if the tag exists already
if git rev-parse "${new_tag}" >/dev/null 2>&1 ; then
	echo "Tag exists already: ${new_tag}" >&2
	exit 1
fi

# Find the previous release commit
prev_subject="UBUNTU: Ubuntu-${version}"
prev_commit=$(git log --format='%H %s' | \
				  grep -m1 -P "^[0-9a-f]{40} ${prev_subject}$" || true)
prev_commit=${prev_commit%% *}
if [ -z "${prev_commit}" ] ; then
	echo "Unable to find previous release commit: ${prev_subject}" >&2
	exit 1
fi

# Add a new changelog section with all the new commit subjects since the
# previous release
{
	echo "linux-firmware (${new_version}) ${release}; urgency=medium"
	echo
	debian/scripts/generate-changelog "${prev_commit}"..
	echo
	echo " -- ${DEBFULLNAME} <${DEBEMAIL}>  $(date -R)"
	echo
	cat debian/changelog
} > debian/changelog.new
mv debian/changelog.new debian/changelog

# Commit the new release
git commit -s -m "UBUNTU: ${new_tag}" -- debian/changelog
debian/scripts/tag-release
