#!/bin/bash -e

TOP=$(cd `dirname $0` ; /bin/pwd)
. $TOP/catkin_util.sh

LONG_USAGE=$(/bin/cat <<EOF
usage: git catkin set-upstream <upstream-repo> <upstream-repo-type>

Creates (if necessary) an orphan branch "catkin" in the current gbp repo and sets
the upstream repo and type in the catkin.conf.  The rest of the catkin utilities
pivot off of these values.

EOF
)
USAGE=$LONG_USAGE
# SUBDIRECTORY_OK=1

. "$(git --exec-path)/git-sh-setup"

UPSTREAM_REPO=$1
if [ $# -lt 2 ] ; then
    echo "${USAGE}"
    exit 1
fi

UPSTREAM_TYPE=$2

case $UPSTREAM_TYPE in
    git) ;;
    svn) ;;
    hg) ;;
    *)
        /bin/echo "What kind of repo type is $UPSTREAM_TYPE?"
        exit 1
        ;;
esac

echo "Upstream ${boldon}$UPSTREAM_REPO${boldoff} type: ${boldon}$UPSTREAM_TYPE${boldoff}"
require_work_tree

if ! git show-ref --heads
then
    status "You're in a freshly initialized repo, no?"
    maybe_continue y "Going to make an empty initial commit in $(pwd)"
    git commit -m "initial commit" --allow-empty
fi

if git show-branch origin/catkin
then
    status "Found remote branch catkin, checking out."
    git checkout catkin
else
    status "No catkin branch... initializing"
    git symbolic-ref HEAD refs/heads/catkin
    rm -f .git/index
    git clean -fdx
    git commit --allow-empty -m "Initial catkin branch"
fi

git config -f catkin.conf catkin.upstream "$UPSTREAM_REPO"
git config -f catkin.conf catkin.upstreamtype "$UPSTREAM_TYPE"

git add catkin.conf
git commit -m "catkin branch update by git-catkin-set-upstream"

exit 0
