#!/usr/bin/env bash


shopt -s globstar

while true ; do
	case $1 in
		-h|--help)
			echo "Usage: $(basename "$0") [OPTIONS] [LIST]"
			echo
			echo "List all repositories in current directory."
			echo
			echo "Options:"
			echo "    -h --help       - print this message and exit"
			echo "    -r --recursive  - list directories recursively"
			echo "    -d --dirs-only  - list directories only"
			echo
			echo "Repository list can be constructed from an existing set of repositories via:"
			echo "  $ git listall > reposiotry.lst"
			echo
			echo "or recursively:"
			echo "  $ git listall -r > reposiotry.lst"
			echo
			echo "If a repository list already exists it can be updated via:"
			echo "  $ git listall -r reposiotry.lst >> reposiotry.lst"
			echo
			echo "For info on list file format see:"
			echo "    $ git-cloneall --help"
			echo
			exit
			;;

		-r|--recursive)
			RECURSIVE=1
			shift
			continue
			;;

		-d|--dirs-only)
			DIRS_ONLY=1
			shift
			continue
			;;

		-u|--update)
			REPOS_FILE=$2
			shift 2
			continue
			;;

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


# prepare putput...
prep(){
	if ! [ -z $DIRS_ONLY ] ; then
		sed -e 's/=.*//'
	else
		cat
	fi
}


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

if ! [ -z $RECURSIVE ] ; then
	REPOS=(./**/.git/config)
else
	REPOS=(./*/.git/config)
fi

if [ -e "$LIST" ] ; then
	echo
	echo "# $(date)"
fi
# format and print unique lines...
lines=()
{
	for p in "${REPOS[@]}" ; do
		path=${p/.git\/config/}
		remote=$(cat "$p" \
			| sed -n '/\[remote "origin"\]/,/^\s*url/p' \
			| grep 'url = ' \
			| sed \
				-e 's/\s*url\s*=\s*//' \
				-e 's/.git\s*$//')
		[ -z $remote ] \
			&& continue
		line="$path=$remote"
		lines+=($line)
		echo $line
	done
	if [ -e "$LIST" ] ; then
		cat "$LIST" \
			| grep -ve '\(^\s*#\|^\s*$\)' \
			| sed \
				-e 's/^-//' \
				-e 's/.git\s*$//'
	fi
} \
	| sort \
	| uniq -u \
	| prep



# vim:set sw=4 ts=4 :
