#!/bin/sh

# load common functions, compatible with local and installed script
. `dirname $0`/../share/eterbuild/functions/common
load_mod git

if [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then
	echo "gpull - do git pull with fast forward only by default."
	echo
	echo "Usage: gpull [-a] [-n] [repo] [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 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 was not uptodate (gpull || echo 'Was updated last time')"
	exit 1
fi

REPO=

if [ "$1" = "-a" ] ; then
	ALLBRANCHES=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)
        # 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_from_unique_branch()
{
        [ -n "$REPO" ] || return
        REMOTEBRANCH=$(git branch -a | grep "^  remotes/$REPO/" | sed -e "s|.*remotes/$REPO/||")
        if [ "$(estrlist count $REMOTEBRANCH)" -gt 1 ] ; then
            fatal "Can't detect remote branch in $REMOTEBRANCH. Run with one from these."
        fi
        docmd git pull $REBASE $REPO $REMOTEBRANCH
}

if [ -n "$ALLBRANCHES" ] ; then
	pull_all_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
# FIXME: Не факт, что удалённо бранч называется именно $REMOTEBRANCH
docmd git pull $REBASE $REPO $REMOTEBRANCH || pull_from_unique_branch || exit

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