#!/bin/bash

source git-hub-helpers

# Safely 
_fork(){
	local FULL_REPO=$1
	local REPO=$2
	local USER=$3

	github /repos/$FULL_REPO/forks >| .tmp_forks

	if [ ! $(cat .tmp_forks | json -a owner.login | fgrep "$(github_user)") ] ; then
		github /repos/$FULL_REPO/forks .tmp_fork
		# Sleep for a moment, to let github register the fork.
		sleep 1
	fi
	echo "Fork at https://github.com/$USER/$REPO"
	rm .tmp_fork*
}

# Clone the repo and set a variety of --local config options for github-flow.
clone(){
	local FULL_REPO=$1
	local REPO=$(echo $FULL_REPO | awk -F/ '{print $2}')
	local USER=$(github_user)

	_fork $FULL_REPO $REPO $USER

	git clone $Q git@github.com:$USER/$REPO.git 2>&1 >/dev/null
	cd $REPO
	git remote add upstream git@github.com:$FULL_REPO.git

	git config --local --add github-flow.origin origin
	git config --local --add github-flow.upstream upstream
	git config --local --add github-flow.master master

	echo "Project cloned into $(pwd)"
}

usage(){
	echo "$0 <org/repo>:	Initialize a new working repository, and set git-hubflow configurations."
}

help(){
	usage
	echo ""
	echo "	<org/repo>: The organization and repository name to clone from."
}

if [ "x$1" == "-h" ] ; then
	help
else
	clone $@
fi
