#!/bin/sh
#
# Copyright (C) 2009-2015, 2017  Etersoft
# Copyright (C) 2009-2015, 2017  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

PROGDIR=$(dirname $0)
[ "$PROGDIR" = "." ] && PROGDIR=$(pwd)

. $PROGDIR/giter-common-functions
. $PROGDIR/giter-git-functions

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
	echo "gpull - do git pull with fast forward only by default."
	echo
	echo "Usage: gpull [options] [remote alias] [branch]"
	echo
	echo "gpull without parameters or with branch name"
	echo "gpull myrepo - for pull from remote myrepo gear repo (with --rebase by default)"
	echo
	echo "Options:"
	echo "   -a  pull all local branches"
	echo "   -A  pull remote branches"
	echo "   -r  rebase during pull"
	echo "   -m  do merge if possible"
	echo "   -f  pull with fast forward only (default)"
	echo "   -c  return error status if repo is just updated (gpull -c || echo 'New commits is received.')"
	exit 0
fi

REPO=

if [ "$1" = "-a" ] ; then
	ALLBRANCHES=1
	shift
fi

if [ "$1" = "-A" ] ; then
	ALLREMOTEBRANCHES=1
	shift
fi

if [ "$1" = "-c" ] ; then
	CHECKRESULT=1
	shift
fi


REBASE="--ff-only"
if [ "$1" = "-r" ] ; then
	REBASE="--rebase"
	shift
fi

if [ "$1" = "-m" ] ; then
	REBASE=""
	shift
fi

if [ "$1" = "-f" ] ; then
	REBASE="--ff-only"
	shift
fi

if is_exist_remote_repo "$1" ; then
	REPO=$1
	shift
fi

pull_all_branches()
{
	local CURRENTBRANCH=$(get_current_branch)
	[ -n "$REPO" ] || REPO=origin

	# pull all branches
	for i in $(get_branch_list) ; do
		docmd git checkout $i || fatal "can't checkout $i"
		docmd git pull --tags $REPO $i
	done
	docmd git checkout $CURRENTBRANCH
}

pull_all_remote_branches()
{
	local CURRENTBRANCH=$(get_current_branch)
	[ -n "$REPO" ] || REPO=origin

	# pull all remote branches
	for branch in $(get_remote_branch_list) ; do
		git branch --track ${branch#remotes/$REPO/} $branch
	done
	docmd git checkout $CURRENTBRANCH
}

# Если не получилось получить обновление по такому же названию бранча, как локальный, то получаем по удалённому
pull_from_unique_branch()
{
	[ -n "$REPO" ] || return
	# TODO: use function for get remote branch name
	REMOTEBRANCH=$(git branch -a | grep "^  remotes/$REPO/" | sed -e "s|.*remotes/$REPO/||")
	if [ "$(estrlist count "$REMOTEBRANCH")" -gt 1 ] ; then
		# use sisyphus name for gear
		# TODO: use function for get url of remote repo
		if rhas "$REMOTEBRANCH" "sisyphus" && get_remote_repo_list -v | grep "^$REPO[[:space:]]" | grep -E -q "/(gears|srpms)/" ; then
			REMOTEBRANCH="sisyphus"
		else
			fatal "Can't detect remote branch in $(echo $REMOTEBRANCH). Run with one from these."
		fi
	fi
	docmd git pull $REBASE $REPO $REMOTEBRANCH
}

if [ -n "$ALLBRANCHES" ] ; then
	pull_all_branches
	# set ff-only merge by default
	set_merge_ff
	exit
fi

if [ -n "$ALLREMOTEBRANCHES" ] ; then
	pull_all_remote_branches
	exit
fi

REMOTEBRANCH="$1"

# Only if set REPO
if [ -n "$REPO" ] ; then
	# use current branch name as default
	[ -n "$REMOTEBRANCH" ] || REMOTEBRANCH=$(get_current_branch)
fi

if [ -n "$CHECKRESULT" ] ; then
	# Quiet in check mode
	#showcmd git pull --rebase $REPO $REMOTEBRANCH
	UPTODATEres=`git pull --rebase $REPO $REMOTEBRANCH 2>&1`
	# REWRITE ME: assure we get tags
	git pull --tags $REPO $REMOTEBRANCH
	echocon "$UPTODATEres"
	echo $UPTODATEres | tail -n1 | grep -q "is up to date"
	exit
fi

docmd git fetch $REPO || exit
set_merge_ff

	# FIXME: Не факт, что удалённо бранч называется именно $REMOTEBRANCH
if ! LC_ALL=C store_output docmd git pull $REBASE $REPO $REMOTEBRANCH ; then
	if grep -qi "fatal: couldn't find remote ref" $RC_STDOUT ; then
		clean_store_output
		pull_from_unique_branch || exit
	elif grep -qi "fatal: not possible to fast-forward, aborting." $RC_STDOUT ; then
		clean_store_output
		info "Try with $ gpull -r if you know what it means."
		exit 1
	else
		clean_store_output
		exit 1
	fi
fi
clean_store_output

# REWRITE ME: assure we get tags
#docmd git pull --tags $REPO $REMOTEBRANCH
docmd git fetch --tags $REPO $REMOTEBRANCH
