#!/usr/bin/env bash

shopt -s globstar

DFL_LIST=repos.lst

while true ; do
	case $1 in
		-h|--help)
			echo "Usage: $(basename "$0") [OPTIONS] FILE"
			echo
			echo "Clone all repositories from lst (FILE)."
			echo
			echo "Options:"
			echo "    -h --help       - print this message and exit"
			echo
			echo "The repository list is a text file containing:"
			echo " - Repository definition lines -- a \"=\"-separated path and a remote url"
			echo "   Repository definitions starting with \"-\" will not get cloned"
			echo " - Lines starting with \"#\" and empty lines are ignored"
			echo
			echo "Example:"
			echo "  # comment..."
			echo "  ./path/to/repo=git@example.com:user/repo.git"
			echo
			echo "  # disabled repo..."
			echo "  -./path/to/other-repo=git@example.com:user/other-repo.git"
			echo
			echo "For info on constructing and updating repository lists see:"
			echo "    $ git-listall --help"
			echo
			exit
			;;

		-*|--*)
			echo "Error: unknown option: \"$1\"" >&2
			exit
			;;
		*)
			LIST=$1
			#TARGET_PATH=$2
			break
			;;
	esac
done


TARGET_PATH=${TARGET_PATH:=.}
cd "$TARGET_PATH"

if [ -z $LIST ] ; then
	if ! [ -e $DFL_LIST ] ; then
		echo "need a list file..." >&2
		exit 1
	fi
	LIST=$DFL_LIST
fi

IFS=$'\n' \
	LIST=($(cat "$LIST"))

wd=`pwd`
for repo in ${LIST[@]} ; do
	repo=`xargs<<<"${repo}"`
	# skip comments and empty lines...
	if [ -z "$repo" ] || [[ "${repo}" =~ ^# ]] ; then
		continue
	fi

	# skip lines startig with "-"...
	if [[ "${repo:0:1}" == "-" ]] ; then
		continue
	fi

	IFS=$'=' \
		repo=($repo)

	# skip existing dirs or local repos...
	if [ -e "${repo[0]}" ] || [ "${repo[1]}" = "origin" ] ; then
		#echo "skipping: ${repo[0]}"
		continue
	fi

	mkdir -p "${repo[0]}"

	git clone ${repo[1]} "${repo[0]}"

	cd "$wd"
done




# vim:set sw=4 ts=4 :
