#!/bin/bash

# Created by jiaqiang.ye@lnxall.com
# Simple repo checkout script
# 2023/11/14

# function to determine the root of a repo-managed project
# It will traverse up all the path to find one.
goto_dotrepo() {
	local cwdir="$1"
	cd "${cwdir}"
	if [ $? -ne 0 ] ; then
		echo "Error, invalid directory: '${cwdir}'" 1>&2
		return 1
	fi

	while true ; do
		[ -d '.repo' ] && return 0
		cd ..
		[ "$(pwd)" = "/" ] && break
	done

	echo "Error, repo-project not found: .repo" 1>&2
	return 2
}

checkout_repo() {
	local rinfo="$(repo info)"
	if [ $? -ne 0 ] ; then
		echo "Error, \`repo info' has failed." 1>&2
		return 1
	fi

	if [ -z "${rinfo}" ] ; then
		echo "Error, \`repo info' has not output." 1>&2
		return 2
	fi

	local REPODIR="$PWD/"       # root directory of repo project
	local DIRLEN=${#REPODIR}    # length of `REPODIR
	local mountp=""             # Mount path:
	local rline=""              # process line-by-line
	echo "${rinfo}" | while read rline ; do
		if [[ "${rline}" =~ ^-+$ ]] ; then
			mountp=""
		elif [[ "${rline}" =~ ^Mount.path:.(.+)$ ]] ; then
			mountp="${BASH_REMATCH[1]}"
			if [ ${#mountp} -lt ${DIRLEN} ] ; then
				echo "Error, invalid mount-path: '${mountp}'" 1>&2
			else
				mountp="${mountp:${DIRLEN}}"
			fi
			[ -z "${mountp}" ] && echo "Error, failed to extract mount-path."
		elif [[ "${rline}" =~ ^Manifest.revision:.(.+)$ ]] ; then
			local bname="${BASH_REMATCH[1]}"
			# echo "Branch: ${bname}, path: ${mountp}"
			[ -n "${bname}" ] && [ -d "${mountp}" ] && cd "${mountp}" && {
				git checkout "${bname}" --
				if [ $? -ne 0 ] ; then
					echo "Error, failed to checkout branch in \"${mountp}\": ${bname}"
					return 3
				fi
				if [ -n "$(git status -uno | grep -e 'nothing to commit')" ] ; then
					git pull --rebase origin "${bname}"
				fi
			}
			cd "${REPODIR}"
		fi
	done
	return 0
}

goto_dotrepo || exit $?
checkout_repo
exit $?
