#!/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 --rebase"
	echo "Use: gpull [-a] [-n] [repo] [branch]"
	echo "     gpull without parameters or with branch name"
	echo "     gpull myrepo - for pull from remote myrepo gear repo (with --rebase by default)"
	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=origin

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

if [ "$1" = "-c" ] ; then
	CHECKONLY=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
            git checkout $i || fatal "can't checkout $i"
            git pull --tags $REPO $i
        done
        git checkout $CURRENTBRANCH
}

if [ -n "$ALLBRANCHES" ] ; then
	pull_all_branches
	exit
fi

if [ -n "$CHECKONLY" ] ; then
	echocon "Pull repo from $REPO"
	UPTODATEres=`git pull --rebase $REPO $@ 2>&1`
	echocon "$UPTODATEres"
	echo $UPTODATEres | tail -n1 | grep -q "is up to date"
	exit
fi

echo "Pull repo from $REPO"
git pull $REBASE $REPO $@ || exit

# assure we get tags
git pull --tags $REPO $@
