#!/bin/sh

set -e

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

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

TARGET=${TARGET#msp}
REPO=$REPO/$TARGET

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 "Checking out $TARGET"
	svn co http://svn.tdb.fi/$REPO/trunk $TARGET >/dev/null
elif [ -d "$TARGET" ]; then
	echo "Updating $TARGET"
	svn up $TARGET >/dev/null
fi

echo $1 >>.mspget-status

for lib in `grep 'require "msp' $TARGET/Build | sed 's/^.*"\(.*\)";/\1/'`; do
	if ! fgrep 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
