#!/bin/sh

if test "z$1" = "z--help" || test "z$1" = "z-h"; then
    echo "place [<destination-dir>]"
    echo "   installs scratch source into the build tree";
    exit 0;
fi

if test "z$1" != "z"; then
    OOBUILDDIR=$1
else
    OOBUILDDIR='@OOBUILDDIR@'
fi

SUBDIRS="canvas-cairo offapi-vba sc-vba mono-uno-bootstrap mono-uno-bridge scsolver lpsolve"
SCRATCHDIR="@TOOLSDIR@/scratch"

BACKUPDIR_SUFFIX="bak"

if [ ! -d "$OOBUILDDIR" ]; then
    echo "Build directory $OOBUILDDIR does not exist";
    return 1;
fi

for subdir in $SUBDIRS; do
	echo "Processing $subdir directory"

	if [ ! -f "$SCRATCHDIR/$subdir/POSITION" ]; then
		echo " - missing $subdir/POSITION file"
		continue
	fi

	POSITION=`cat "$SCRATCHDIR/$subdir/POSITION"`
	TARGETDIR="$OOBUILDDIR/$POSITION"

	if [ -h "$SCRATCHDIR/$subdir" ]; then
		echo " - symlink exists, skipping"
		continue
	fi
	
	if [ -d "$TARGETDIR" ]; then
	    echo " - renaming original directory (adding .$BACKUPDIR_SUFFIX)"
	    mv "$TARGETDIR" "$TARGETDIR.$BACKUPDIR_SUFFIX"
        fi

	echo " - moving $subdir"
	mv "$SCRATCHDIR/$subdir" "$TARGETDIR"

	echo " - linking back"
	ln -s "$TARGETDIR" "$SCRATCHDIR/$subdir"
done

