#!/bin/bash

# Input:
# $TAG - the SVN tag to export
# $BRANCH - the SVN branch to export
# (exactly one among $TAG and $BRANCH must be specified)
# $VERSION - the upstream version of the generated tarball
# $REVISION (optional) - export a specific revision of the SVN repository
# $ONLYFILTER - if not null, don't download the tarball from the SVN; just re-filter its content

DESTDIR="../tarballs/geogebra-$VERSION"
DESTTGZ="../tarballs/geogebra_$VERSION.orig.tar.gz"
TEMPDIR="$(mktemp -d)"

# Files that need to be retained from the JUNG library
JUNG_FILES="AbstractGraph.java EdgeType.java Pair.java Graph.java MultiGraph.java Hypergraph.java SparseMultigraph.java Distance.java ShortestPath.java MapBinaryHeap.java BasicMapEntry.java DijkstraShortestPath.java DijkstraDistance.java"

if [ "x$ONLYFILTER" == "x" ] ; then
	# Downloads code from SVN repository
	test -d ../tarballs/. || mkdir -p ../tarballs
	if [ "x$TAG" == "x" ] ; then
		SVNDIR="branches/$BRANCH/geogebra/"
	else
		SVNDIR="tags/$TAG/geogebra/"
	fi
	if [ "x$REVISION" == "x" ] ; then
		svn export "http://dev.geogebra.org/svn/$SVNDIR" "$DESTDIR"
	else
		svn export -r "$REVISION" "http://dev.geogebra.org/svn/$SVNDIR" "$DESTDIR"
	fi
else
	# Uncompress the previous tarball
	tar xzfv "$DESTTGZ" -C `dirname "$DESTDIR"`
fi

# Remove embedded copies of other software
rm -vfr "$DESTDIR/org"
rm -vfr "$DESTDIR/edu/jas"
rm -vfr "$DESTDIR/edu/mas"
echo find "$DESTDIR/edu/uci" -type f $(echo $JUNG_FILES | tr ' ' '\n' | sed 's:^:-a ! -wholename '\''*/:;s:$:'\'':') -delete | sh

# tabber.js is minimized and must be downloaded in its original form
rm -vf "$DESTDIR/geogebra/export/tabber.js"
wget -O "$DESTDIR/geogebra/export/tabber.js" "http://www.barelyfitz.com/projects/tabber/tabber.js"

# Remove other unecessary files
rm -vfr "$DESTDIR/installer"
rm -vfr "$DESTDIR/webstart"
rm -vfr "$DESTDIR/scripts"
rm -vfr "$DESTDIR/javacc"

# Remove all upstream JARs, DLLs, SOs and JNILIBs
for ext in jar dll so jnilib ; do
	find "$DESTDIR" -iname '*'."$ext" -print0 | xargs -0 rm -vf
done

# Remove empty directories (that tend to confuse git)
find "$DESTDIR" -type d -empty -delete

# Build tarball
tar czfv "$DESTTGZ" -C `dirname "$DESTDIR"` `basename "$DESTDIR"`

# Delete snapshot and temporary dir
rm -fr "$DESTDIR"
rm -fr "$TEMPDIR"

