#!/bin/sh

#when forking a repo from github, one might need to mask imports in a package
#this scripts checks for the existence of a local package with the same name
#and links/unlinks the remote into the local. 
#so let's say that you fork on github https://github.com/foo/bar and you are baz.
#you would git clone git@github.com:baz/bar.git but it would contain all the upstream imports
#using this scipt you will be able to fool your go installation to point them to your local copy.
#by doing: gogithub mask foo/bar 
#and restoring it by: gogithub unmask foo/bar

checkexistence() {
	localpkg=${1#*/}
	if [ -L "${GOPATH-}/src/github.com/$1" ] && [ -e "${GOPATH}/src/${localpkg}" ]; then
		echo "link found. already masked"
	elif ! [ -e "${GOPATH}/src/github.com/$1" ] || ! [ -e "${GOPATH}/src/${localpkg}" ]; then
		echo "package with the same name not found under ${GOPATH}/src/github.com and ${GOPATH}/src"
		exit 1
	fi
}

mask() {
	echo "masking" "$1"
	localpkg=${1#*/}
	checkexistence "$1"
	if [ -e "${GOPATH}/src/github.com/$1-upstream" ]; then
		echo "package has been already masked. resolve manually"
		exit 1
	fi
	mv "${GOPATH}/src/github.com/$1" "${GOPATH}/src/github.com/$1-upstream"
	ln -s "${GOPATH}/src/${localpkg}" "${GOPATH}/src/github.com/$1"
	exit 0
}

unmask() {
	echo "unmasking" "$1"
	checkexistence "$1"
	if ! [ -e "${GOPATH}/src/github.com/$1-upstream" ]; then
		echo "package has been not been masked."
		exit 1
	fi
	rm "${GOPATH}/src/github.com/$1"
	mv "${GOPATH}/src/github.com/$1-upstream" "${GOPATH}/src/github.com/$1"
	exit 0
}

usage() {
	echo "$0" " [mask|unmask] pkgname"
	exit 1
}

if [ ${#} -eq 0 ] || [ ${#} -gt 2 ]; then 
	usage
elif [ "$1" = "mask" ]; then
	mask "$2"
elif [ "$1" = "unmask" ]; then
	unmask "$2"
else
	usage
fi
