#!/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 branch -D "${bname}" >/dev/null 2>/dev/null
				git checkout -b "${bname}"
			}
			cd "${REPODIR}"
		fi
	done
	return 0
}

ckout_tag() {
	local top_path=$(pwd)
	local lib_opt_cfg=$1
	shift
	default_xml=$(cat .repo/manifest.xml | grep "default.xml" -wc)
	if [ "$default_xml" -eq 0 ]; then
		echo "not the default XML"
		return 0
	fi
	#
	. ./wlos_core/scripts/checkout_tag.sh > /dev/null 2>&1
	checkout_tag $lib_opt_cfg
}

lib_opt=$(realpath $1) > /dev/null 2>&1
goto_dotrepo || exit $?
checkout_repo || exit $?
if [ -n "$lib_opt" ]; then
	ckout_tag $lib_opt; exit $?
fi
