#!/bin/sh
# mspget.sh version 0.2.2

set -e

TARGET=$1
if [ -z "$TARGET" ]; then
	echo "mspget.sh - check out MSP software from git"
	echo "Usage: $0 <package>"
	exit
fi

REPO=
if [ "${TARGET#lib}" != "$TARGET" ]; then
	REPO=libs/
	TARGET=${TARGET#lib}
fi

TARGET=${TARGET#msp}
REPO=$REPO$TARGET.git

if [ -z "$MSPGET_LEVEL" ]; then
	MSPGET_LEVEL=1
	echo >.mspget-status
	trap "rm -f .mspget-status" EXIT
else
	MSPGET_LEVEL=$(($MSPGET_LEVEL+1))
fi
export MSPGET_LEVEL

if [ ! -e "$TARGET" ]; then
	echo "Cloning $TARGET"
	git clone -q git://git.tdb.fi/$REPO >/dev/null
elif [ -d "$TARGET/.git" ]; then
	echo "Pulling $TARGET"
	(cd $TARGET && git pull -q >/dev/null)
fi

echo $1 >>.mspget-status

for lib in `grep 'require "msp' $TARGET/Build | sed 's/^.*"\(.*\)";/\1/'`; do
	if ! grep "^lib$lib\$" .mspget-status >/dev/null; then
		sh $0 lib$lib
	fi
done

if [ "$MSPGET_LEVEL" = 1 ]; then
	echo
	echo "All done."
	if [ ! -d builder ]; then
		echo "You seem to lack builder, which is required for building MSP software."
		echo "To get builder, execute $0 builder"
	elif [ "$TARGET" = builder ]; then
		echo "You have just downloaded builder.  To build it, cd to the builder directory"
		echo "and run the script bootstrap.sh there."
	else
		echo "To build $1, cd to the $TARGET directory and run builder."
	fi
fi
