# $Id$
# vim:et:ft=sh:sts=2:sw=2
#
# git-flow -- A collection of Git extensions to provide high-level
# repository operations for Vincent Driessen's branching model.
#
# A blog post presenting this model is found at:
#    http://blog.avirtualhome.com/development-workflow-using-git/
#
# Feel free to contribute to this project at:
#    http://github.com/petervanderdoes/gitflow
#
# Authors:
# Copyright 2012-2019 Peter van der Does. All rights reserved.
#
# Original Author:
# Copyright 2010 Vincent Driessen. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

#
# Function used by finish command to actually finish the release branch
# Called when the base of the release is the $DEVELOP_BRANCH
#
_finish_from_develop() {
	local opts merge_branch commit keepmsg remotebranchdeleted localbranchdeleted compare_refs_result merge_result

	remotebranchdeleted=$FLAGS_FALSE
	localbranchdeleted=$FLAGS_FALSE

	# Update local branches with remote branches
	if flag fetch; then
		git_fetch_branch "$ORIGIN" "$MASTER_BRANCH"
		git_fetch_branch "$ORIGIN" "$DEVELOP_BRANCH"
	fi

	# Check if the local branches have all the commits from the remote branches
	if git_remote_branch_exists "$ORIGIN/$BRANCH"; then
		require_branches_equal "$BRANCH" "$ORIGIN/$BRANCH"
	fi
	if git_remote_branch_exists "$ORIGIN/$MASTER_BRANCH"; then
		if flag ff_master; then
			git_compare_refs "$MASTER_BRANCH" "$ORIGIN/$MASTER_BRANCH"
			compare_refs_result=$?

			if [ $compare_refs_result -gt 0 ]; then
				warn "Branches '"$MASTER_BRANCH"' and '"$ORIGIN/$MASTER_BRANCH"' have diverged."
				if [ $compare_refs_result -eq 1 ]; then
					warn "Fast forwarding '"$MASTER_BRANCH"'."
					git_do checkout "$MASTER_BRANCH" || die "Could not check out branch '$MASTER_BRANCH'."
					git_do merge  --ff-only "$ORIGIN/$MASTER_BRANCH" >/dev/null 2>&1
					merge_result=$?
					git_do checkout "$BRANCH"
					if [ $merge_result -gt 0 ]; then
						die "'"$MASTER_BRANCH"' can not be fast forwarded."
					fi
				elif [ $compare_refs_result -eq 2 ]; then
					# Warn here, since there is no harm in being ahead
					warn "And local branch '$1' is ahead of '$2'."
				else
					die "Branches need merging first."
				fi
			fi
		else
			require_branches_equal "$MASTER_BRANCH" "$ORIGIN/$MASTER_BRANCH"
		fi
	fi
	if git_remote_branch_exists "$ORIGIN/$DEVELOP_BRANCH"; then
		require_branches_equal "$DEVELOP_BRANCH" "$ORIGIN/$DEVELOP_BRANCH"
	fi

	if noflag notag; then
		# We ask for a tag, be sure it does not exists or
		# points to the latest hotfix commit
		if git_tag_exists "$VERSION_PREFIX$TAGNAME"; then
			git_compare_refs  "$BRANCH" "$VERSION_PREFIX$TAGNAME"^2 2>/dev/null
			[ $? -eq 0 ] || die "Tag already exists and does not point to release branch '$BRANCH'"
		fi
	fi

	run_pre_hook "$VERSION_PREFIX$TAGNAME" "$ORIGIN" "$BRANCH"

	# Try to merge into master.
	# In case a previous attempt to finish this release branch has failed,
	# but the merge into master was successful, we skip it now
	if ! git_is_branch_merged_into "$BRANCH" "$MASTER_BRANCH"; then
			git_do checkout "$MASTER_BRANCH" || die "Could not check out branch '$MASTER_BRANCH'."
			if noflag squash; then
				git_do merge --no-ff "$BRANCH" || die "There were merge conflicts." # TODO: What do we do now?
			else
				git_do merge --squash "$BRANCH" || die "There were merge conflicts." # TODO: What do we do now?
				flag squash_info && gitflow_create_squash_message "Merged release branch '$BRANCH'" "$MASTER_BRANCH" "$BRANCH" > "$DOT_GIT_DIR/SQUASH_MSG"
				git_do commit
			fi
	fi

	if noflag notag; then
		# Try to tag the release.
		# In case a previous attempt to finish this release branch has failed,
		# but the tag was set successful, we skip it now
		if ! git_tag_exists "$VERSION_PREFIX$TAGNAME"; then
			git_do checkout "$MASTER_BRANCH" || die "Could not check out branch '$MASTER_BRANCH'."
			if [ "$FLAGS_message" != "" ] && [ "$FLAGS_messagefile" != "" ]; then
				die "Use either -m,--message or -f,--messagefile. Can not use both options at the same time"
			fi
			opts="-a"
			flag sign && opts="$opts -s"
			[ "$FLAGS_signingkey" != "" ] && opts="$opts -u '$FLAGS_signingkey'"
			if [ "$FLAGS_message" != "" ]; then
				# Run filter on the tag message
				FLAGS_message=$(run_filter_hook release-finish-tag-message "${FLAGS_message}" "$VERSION_PREFIX$TAGNAME")
				opts="$opts -m '$FLAGS_message'"
			fi
			[ "$FLAGS_messagefile" != "" ] && opts="$opts -F '$FLAGS_messagefile'"
			eval git_do tag $opts "$VERSION_PREFIX$TAGNAME" || die "Tagging failed. Please run finish again to retry."
		fi
	fi

	# By default we backmerge the $MASTER_BRANCH unless the user explicitly
	# stated not to do a back merge, in that case we use the $BRANCH.
	if noflag nobackmerge; then
		merge_branch="$MASTER_BRANCH"
	else
		merge_branch="$BRANCH"
	fi

	# Try to merge into develop unless 'nodevelopmerge' has been specified.
	# In case a previous attempt to finish this release branch has failed,
	# but the merge into develop was successful, we skip it now
	if noflag nodevelopmerge; then
		if ! git_is_branch_merged_into "$merge_branch" "$DEVELOP_BRANCH"; then
			git_do checkout "$DEVELOP_BRANCH" || die "Could not check out branch '$DEVELOP_BRANCH'."

			if noflag nobackmerge; then
				# Accounting for 'git describe', if a release is tagged
				# we use the tag commit instead of the branch.
				if noflag notag; then
					commit="$VERSION_PREFIX$TAGNAME"
				else
					commit="$MASTER_BRANCH"
				fi
				git_do merge --no-ff "$commit" || die "There were merge conflicts." # TODO: What do we do now?
			else
				commit="$BRANCH"
				if noflag squash; then
					git_do merge --no-ff "$commit" || die "There were merge conflicts." # TODO: What do we do now?
				else
					git_do merge --squash "$commit" || die "There were merge conflicts." # TODO: What do we do now?
					flag squash_info && gitflow_create_squash_message "Merged release branch '$BRANCH'" "$DEVELOP_BRANCH" "$BRANCH" > "$DOT_GIT_DIR/SQUASH_MSG"
					git_do commit
				fi
			fi
		fi
	fi

	run_post_hook "$VERSION_PREFIX$TAGNAME" "$ORIGIN" "$BRANCH"

	if flag push; then
		if flag pushdevelop; then
			git_do push "$ORIGIN" "$DEVELOP_BRANCH" || die "Could not push branch '$DEVELOP_BRANCH' to remote '$ORIGIN'."
		fi
		if flag pushproduction; then
			git_do push "$ORIGIN" "$MASTER_BRANCH" || die "Could not push branch '$MASTER_BRANCH' to remote '$ORIGIN'."
		fi
		if noflag notag && flag pushtag; then
			git_do push --tags "$ORIGIN" || die "Could not push tags to remote '$ORIGIN'."
		fi
	fi

	# Delete branch
	if noflag keep; then

		if [ "$BRANCH" = "$(git_current_branch)" ]; then
			git_do checkout "$MASTER_BRANCH" || die "Could not check out branch '$MASTER_BRANCH'."
		fi

		# Always delete remote first
		if noflag keepremote;then
			if git_remote_branch_exists "$ORIGIN/$BRANCH"; then
				git_remote_branch_delete "$BRANCH" && remotebranchdeleted=$FLAGS_TRUE
			fi
		fi

		# Delete local after remote to avoid warn