#!/usr/bin/env sh

# Download specified branch.
# Usage: download_repo REPO BRANCH DIR
# Use '--' for primary branch.
download_repo () {
	local REPO="$1"
	local BRANCH="$2"
	local DIR="$3"
	#local DIR_PATH=$(pwd)"/${DIR}"
	local DIR_PATH="${DIR}"

	if [ "x${REPO}" = "x" -o "x${BRANCH}" = "x" -o "x${DIR}" = "x" ]; then
		echo "Missing parameters in download_repo()." >&2
		exit 1
	fi

	if [ ! -e "${DIR}" ]; then
		git clone "${REPO}" "${DIR}" || exit 1
	fi

	if [ -d "${DIR}" -a -x "${DIR}" -a -w "${DIR}" ]; then
		GIT_DIR="${DIR}/.git"
		if [ ! -d "${GIT_DIR}" ]; then
			echo echo "'${DIR_PATH}' is not a git repository." >&2
		fi
	fi

	if [ ! -d "${DIR}" -o ! -x "${DIR}" -o ! -w "${DIR}" ]; then
		echo "'${DIR_PATH}' is not a writeable directory." >&2
		exit 1
	fi

	cd "${DIR}"

	git clean -fd
	git clean -fx
	git checkout -- . || exit 1
	if [ "x${BRANCH}" != "x--" ]; then
		git checkout "${BRANCH}" || exit 1
	fi
	git pull || exit 1

	cd ..
}

# Clone a specific branch, only the latest commit without history.
# # Download specified branch.
# Usage: download_repo_branch_head REPO BRANCH DIR
# Use '--' for primary branch.
download_repo_branch_head () {
	local REPO="$1"
	local BRANCH="$2"
	local DIR="$3"
	#local DIR_PATH=$(pwd)"/${DIR}"
	local DIR_PATH="${DIR}"

	if [ "x${REPO}" = "x" -o "x${BRANCH}" = "x" -o "x${DIR}" = "x" ]; then
		echo "Missing parameters in download_repo_branch_head()." >&2
		exit 1
	fi

	if [ ! -e "${DIR}" ]; then
		if [ "x${BRANCH}" != "x--" ]; then
			git clone -b ${BRANCH} --depth 1  --single-branch "${REPO}" "${DIR}" || exit 1
		else
			git clone --depth 1  --single-branch "${REPO}" "${DIR}" || exit 1
		fi
	fi

	if [ -d "${DIR}" -a -x "${DIR}" -a -w "${DIR}" ]; then
		GIT_DIR="${DIR}/.git"
		if [ ! -d "${GIT_DIR}" ]; then
			echo echo "'${DIR_PATH}' is not a git repository." >&2
		fi
	fi

	if [ ! -d "${DIR}" -o ! -x "${DIR}" -o ! -w "${DIR}" ]; then
		echo "'${DIR_PATH}' is not a writeable directory." >&2
	fi
}
