#!/bin/bash

# Run this from the top-level vamp-build-and-test directory
# Optional argument for the single repo to checkout; default is all of them

single=""
if [ -n "$1" ]; then
    single="$1"
fi

set -eu

failed=/tmp/failed_$$
rm -f "$failed"
trap "rm -f $failed" 0

cat METADATA/repos.txt | grep -v '^#' | awk -F= '{ print $1, $2 }' |
    while read name loc; do
        if [ -n "$single" ]; then
            if [ "$single" != "$name" ]; then
                continue
            fi
        fi
	if [ -d "$name"/.hg ]; then 
 	    ( cd $name ; hg pull && hg update ) || echo "$name" >> "$failed"
	elif [ -d "$name"/.git ]; then 
 	    ( cd $name ; git pull ) || echo "$name" >> "$failed"
	elif [ -d "$name" ]; then
	    echo "ERROR: Directory \"$name\" exists, but is not a git or hg repo" 1>&2
	    exit 1
	else
	    case "$loc" in
		*/hg/*)
		    hg clone "$loc" "$name" || echo "$name" >> "$failed";;
		*//git*)
		    git clone "$loc" "$name" || echo "$name" >> "$failed";;
		*)
		    echo "ERROR: Can't deduce repo type from URL \"$loc\"" 1>&2
		    exit 1;;
	    esac
	fi
    done

echo "Done"
if [ -f "$failed" ]; then
    echo "Failed repos:"
    cat "$failed"
fi
