#!/bin/sh

origin=`git remote -v | grep ^origin | grep "[(]fetch[)]" | cut -f2 | cut -f1 -d\    `
current=`git branch -a | grep "^[*] " | cut -f2 -d\   `

case "$current" in
topic-*)
    echo "*** cannot re-origin from topic branch"
    exit 1
    ;;
esac

if test -z "$1" ; then
    echo "$origin $current"
    exit 0
fi

target="$1"
if test ! -z "$origin" ; then
    git remote rename origin origin-old ; fi

if git remote add origin ${1} ; then
    if git update origin $current ; then
        git push --set-upstream origin $current
        git remote rm origin-old
        exit 0
    fi 
    git remote rm origin
fi

if test ! -z "$origin" ; then
    git remote rename origin-old origin ; fi

