#!/bin/bash

if ! hub fork --help > /dev/null; then
    echo "Please, install https://github.com/github/hub plugin.";
    exit 1
fi

SRC_GITHUB_USER=${SRC_GITHUB_USER:=theorchard}
SRC_REMOTE_NAME=${SRC_REMOTE_NAME:=$SRC_GITHUB_USER}

function usage {
    echo "Usage: `basename $0` repo_name [github_user_name]"
    exit 1
}

if [[ $# -lt 1 ]]; then
    usage
fi

REPO_NAME=$1

if [[ $# -eq 2 ]]; then
    GITHUB_USER=$2
else
    GITHUB_USER=`git config --get github.user`
    if [[ -z ${GITHUB_USER} ]]; then
        echo "Make sure you have github username set in .gitconfig or pass it explicitly"
        usage
    fi
fi

set -e -u

git clone git@github.com:${SRC_GITHUB_USER}/${REPO_NAME}.git
cd ${REPO_NAME}
hub fork
git remote rename origin ${SRC_REMOTE_NAME}
git remote rename ${GITHUB_USER} origin
git remote set-url --push ${SRC_REMOTE_NAME} do-not-push-here
git remote -v
git config branch.master.remote ${SRC_REMOTE_NAME}
git config branch.master.merge refs/heads/master
