#!/bin/bash
# 
# Clone repository from mirror
#
# Usage:
#  cclone <main repo url> [ -p <path> ] [ -c <checkout_ref> ]

# strict mode
set -euo pipefail
IFS=$'\n\t'

# include config
source $(dirname $(realpath $0))/config
source $(dirname $(realpath $0))/gen-mirror-path

# parse arguments
function usage(){
	echo "Usage: $0 [-p <path>] [-c <checkout_ref>]" 1>&2
	exit 1
}

repo=$1

if [[ ! "$repo" =~ ^-.* ]]
then
	# check if repo was mirrored
	if [ ! -d $(getRepoPath $repo) ]
	then
		echo "Specified repo wasn't mirrored yes, please do it so!" 1>&2
		exit 1
	fi
	# kick args +1 
	shift
else 
	usage
fi

# other opts
while getopts "c:p:" o; do
	case "${o}" in
		c)
			param_c=${OPTARG}
			;;
		p)
			param_p=${OPTARG}
			;;
		\?)
			usage
			;;
	esac
done


# Run clone
cloneurl=$(getRepoPath $repo)
clonepath=${param_p:-}

echo "Cloning $repo"
git clone file://$cloneurl $clonepath

checkout=${param_c:-}
if [ -n "$checkout" ] 
then
	chdir=${param_p:-$(getRepoUniq $repo)}
	echo "Checking out $checkout"
	oldpwd=$(pwd)
	cd $chdir
	# -b just to make git less verbose
	git checkout $checkout -b _tmp_$checkout
	cd $oldpwd
fi