#!/bin/bash -e

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

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

Creates (if necessary) an orphan branch "bloom" in the current gbp repo and sets
the upstream repo and type in the bloom.conf.  The rest of the bloom 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/bloom
then
    status "Found remote branch bloom, checking out."
    git checkout bloom
else
    status "No bloom branch... initializing"
    git symbolic-ref HEAD refs/heads/bloom
    rm -f .git/index
    git clean -fdx
    git commit --allow-empty -m "Initial bloom branch"
fi

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

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

exit 0
