#!/bin/bash

#pull and checks out all branches - note it will merge all remotes with local branches!

#assumes you want to replace your current origin and you want to make git.soton.ac.uk the new origin with "gitlab/github" as a remote called "gitlab/github"
#assumes you have set up a repo on git.soton.ac.uk with the same name as the original repo on another server

sotonuser="etfr"
from="origin"
to="git.soton.ac.uk"

usage()
{
    echo "usage: port_git.sh [[[-f file ] [-i]] | [-h]]"
}

pull=1
push=1
while [ "$1" != "" ]; do
    case $1 in
        --no-push )           	push=0
                                ;;
        --no-pull )           	pull=0
                                ;;								
        -s | --simple )    		pull=0
								push=0
                                ;;
        -h | --help )           usage
                                exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done

reponame=$(git remote get-url $from | awk -F'/' '{ print $NF }')
old_label=$(git remote get-url $from | sed 's/.*@//' | sed 's/\..*//')


#make sure all remote branches are tracked locally
git fetch $from
if [ "$pull" = "1" ]; then
	for remote in $(git branch -r | grep -v '\->'); do 
		git branch --track "${remote#$from/}" "$remote" 2>/dev/null || 
		git branch --set-upstream-to="$remote" "${remote#$from/}"; 
	done
	git pull --all
fi

git remote rename "$from" "$old_label"

git remote add $from "git@$to:$sotonuser/$reponame"
git fetch $from
if [ "$push" = "1" ]; then
	git push -u --all $from
else
	for branch in  $(git for-each-ref refs/heads --format='%(refname)'); do
		bare_branch="${branch##refs/heads/}"
		echo "Setting up branch $bare_branch"
		git branch --track "$bare_branch" "$from/$bare_branch" 2>/dev/null || 
		git branch --set-upstream-to="$from/$bare_branch" "$bare_branch"; 
	done	
fi
