# $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.
#

initialize() {
	require_git_repo
	require_gitflow_initialized
	git config --get gitflow.prefix.bugfix >/dev/null 2>&1 || die "Bugfix prefix not set. Please run 'git flow init'."
	gitflow_load_settings
	PREFIX=$(git config --get gitflow.prefix.bugfix)
}

usage() {
	OPTIONS_SPEC="\
git flow bugfix [list]
git flow bugfix start
git flow bugfix finish
git flow bugfix publish
git flow bugfix track
git flow bugfix diff
git flow bugfix rebase
git flow bugfix checkout
git flow bugfix pull
git flow bugfix delete

Manage your bugfix branches.

For more specific help type the command followed by --help
--
"
	flags_help
}

cmd_default() {
	cmd_list "$@"
}

cmd_list() {
	OPTIONS_SPEC="\
git flow bugfix [list] [-h] [-v]

Lists all the existing bugfix branches in the local repository.
--
h,help!     Show this help
v,verbose   Verbose (more) output
"
	local bugfix_branches current_branch width branch len
	local base develop_sha branch_sha

	# Define flags
	DEFINE_boolean 'verbose' false 'verbose (more) output' v

	# Parse argun=ments
	parse_args "$@"

	bugfix_branches=$(git_local_branches_prefixed "$PREFIX")
	if [ -z "$bugfix_branches" ]; then
		warn "No bugfix branches exist."
		warn ""
		warn "You can start a new bugfix branch:"
		warn ""
		warn "    git flow bugfix start <name> [<base>]"
		warn ""
		exit 0
	fi
	current_branch=$(git_current_branch)

	# Determine column width first
	width=0
	for branch in $bugfix_branches; do
		len=${#branch}
		width=$(max $width $len)
	done
	width=$(($width+3-${#PREFIX}))

	for branch in $bugfix_branches; do
		base=$(git merge-base "$branch" "$DEVELOP_BRANCH")
		develop_sha=$(git rev-parse "$DEVELOP_BRANCH")
		branch_sha=$(git rev-parse "$branch")
		if [ "$branch" = "$current_branch" ]; then
			printf "* "
		else
			printf "  "
		fi
		if flag verbose; then
			printf "%-${width}s" "${branch#$PREFIX}"
			if [ "$branch_sha" = "$develop_sha" ]; then
				printf "(no commits yet)"
			elif [ "$base" = "$branch_sha" ]; then
				printf "(is behind develop, may ff)"
			elif [ "$base" = "$develop_sha" ]; then
				printf "(based on latest develop)"
			else
				printf "(may be rebased)"
			fi
		else
			printf "%s" "${branch#$PREFIX}"
		fi
		echo
	done
}

cmd_help() {
	usage
	exit 0
}

# Parse arguments and set common variables
parse_args() {
	FLAGS "$@" || exit $?
	eval set -- "${FLAGS_ARGV}"

	# read arguments into global variables
	if [ -z $1 ]; then
		NAME=''
	else
		NAME=$1
	fi
	BRANCH=$PREFIX$NAME
}

parse_remote_name() {
	# Parse arguments
	FLAGS "$@" || exit $?
	eval set -- "${FLAGS_ARGV}"

	# read arguments into global variables
	if [ -z $1 ]; then
		REMOTE=''
	else
		REMOTE=$1
	fi

	if [ -z $2 ]; then
		NAME=''
	else
		NAME=$2
	fi
	BRANCH=$PREFIX$NAME
}

cmd_start() {
	OPTIONS_SPEC="\
git flow bugfix start [-h] [-F] <name> [<base>]

Start new bugfix <name>, optionally basing it on <base> instead of <develop>
--
h,help!          Show this help
showcommands!    Show git commands while executing them
F,[no]fetch      Fetch from origin before performing local operation
"
	local base

	# Define flags
	DEFINE_boolean 'fetch' false 'fetch from origin before performing local operation' F

	# Override defaults with values from config
	gitflow_override_flag_boolean   "bugfix.start.fetch"   "fetch"

	# Parse arguments
	parse_args "$@"
	eval set -- "${FLAGS_ARGV}"
	base=${2:-$DEVELOP_BRANCH}

	require_base_is_local_branch "$base"
	gitflow_require_name_arg

	# Update the local repo with remote changes, if asked
	if flag fetch; then
		git_fetch_branch "$ORIGIN" "$base"
	fi

	# Sanity checks
	require_branch_absent "$BRANCH"

	# If the origin branch counterpart exists, assert that the local branch
	# isn't behind it (to avoid unnecessary rebasing)
	if git_remote_branch_exists "$ORIGIN/$base"; then
		require_branches_equal "$base" "$ORIGIN/$base"
	fi

	run_pre_hook "$NAME" "$ORIGIN" "$BRANCH" "$base"

	gitflow_config_set_base_branch $base $BRANCH

	# create branch
	git_do checkout -b "$BRANCH" "$base" || die "Could not create bugfix branch '$BRANCH'."

	run_post_hook "$NAME" "$ORIGIN" "$BRANCH" "$base"

	echo
	echo "Summary of actions:"
	echo "- A new branch '$BRANCH' was created, based on '$base'"
	echo "- You are now on branch '$(git_current_branch)'"
	echo ""
	echo "Now, start committing on your bugfix. When done, use:"
	echo ""
	echo "     git flow bugfix finish $NAME"
	echo
}

cmd_finish() {
	OPTIONS_SPEC="\
git flow bugfix finish [-h] [-F] [-r] [-p] [-k] [-D] [-S] [--no-ff] <name|nameprefix>

Finish bugfix <name>
--
h,help!                Show this help
showcommands!          Show git commands while executing them
F,[no]fetch            Fetch from origin before performing finish
r,[no]rebase           Rebase before merging
p,[no]preserve-merges  Preserve merges while rebasing
[no]push               Push to origin after performing finish
k,[no]keep             Keep branch after performing finish
keepremote!        	   Keep the remote branch
keeplocal!             Keep the local branch
D,[no]force_delete     Force delete bugfix branch after finish
S,[no]squash           Squash bugfix during merge
no-ff!                 Never fast-forward during the merge
"
	local finish_base

	# Define flags
	DEFINE_boolean 'fetch' false "fetch from $ORIGIN before performing finish" F
	DEFINE_boolean 'rebase' false "rebase before merging" r
	DEFINE_boolean 'preserve-merges' false 'try to recreate merges while rebasing' p
	DEFINE_boolean 'push' false "push to $ORIGIN after performing finish"
	DEFINE_boolean 'keep' false "keep branch after performing finish" k
	DEFINE_boolean 'keepremote' false "keep the remote branch"
	DEFINE_boolean 'keeplocal' false "keep the local branch"
	DEFINE_boolean 'force_delete' false "force delete bugfix branch after finish" D
	DEFINE_boolean 'squash' false "squash bugfix during merge" S
	DEFINE_boolean 'squash-info' false "add branch info during squash"
	DEFINE_boolean 'no-ff!' false "Don't fast-forward ever during merge "

	# Override defaults with values from config
	gitflow_override_flag_boolean   "bugfix.finish.fetch"             "fetch"
	gitflow_override_flag_boolean   "bugfix.finish.rebase"            "rebase"
	gitflow_override_flag_boolean   "bugfix.finish.preserve-merges"   "preserve_merges"
	gitflow_override_flag_boolean   "bugfix.finish.push"              "push"
	gitflow_override_flag_boolean   "bugfix.finish.keep"              "keep"