#!/bin/bash

# Input:
# $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/mathpiper-$VERSION"
DESTTGZ="../tarballs/mathpiper_$VERSION.orig.tar.gz"

if [ "x$ONLYFILTER" == "x" ] ; then
	# Downloads code from SVN repository
	test -d ../tarballs/. || mkdir -p ../tarballs
	if [ "x$REVISION" == "x" ] ; then
		svn export "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mathpiper" "$DESTDIR"
		svn export "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mpreduce/src/java/org/mathpiper/mpreduce" "$DESTDIR/src/org/mathpiper/mpreduce"
		svn export "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mpreduce/src/packages" "$DESTDIR/src/packages"
		mkdir "$DESTDIR/lib"
		svn export "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mpreduce/lib/build_scripts" "$DESTDIR/lib/build_scripts"
	else
		svn export -r "$REVISION" "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mathpiper" "$DESTDIR"
		svn export -r "$REVISION" "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mpreduce/src/java/org/mathpiper/mpreduce" "$DESTDIR/src/org/mathpiper/mpreduce"
		svn export -r "$REVISION" "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mpreduce/src/packages" "$DESTDIR/src/packages"
		mkdir "$DESTDIR/lib"
		svn export -r "$REVISION" "http://mathpiper.googlecode.com/svn/trunk/src/library_apps/mpreduce/lib/build_scripts" "$DESTDIR/lib/build_scripts"
	fi
else
	# Uncompress the previous tarball
	tar xzfv "$DESTTGZ" -C `dirname "$DESTDIR"`
fi

# Removes embedded copies of other software
rm -vfr "$DESTDIR/src/org/mathpiper/ui/gui/jmathtex"
rm -vfr "$DESTDIR/src/org/apache"
rm -vfr "$DESTDIR/src/org/matheclipse"
rm -vfr "$DESTDIR/src/org/scilab"
rm -vfr "$DESTDIR/src/edu"

# Remove other unecessary files
rm -vfr "$DESTDIR/misc"
rm -vf "$DESTDIR/src/org/mathpiper/test/matheclipse/ParseRubiFiles.java"
rm -vf "$DESTDIR/src/org/mathpiper/builtin/functions/optional/ViewGeoGebra.java"

# Remove other files with problematic licenses
rm -f "$DESTDIR/lib/build_scripts/buildcsl.lsp"
rm -f "$DESTDIR/lib/build_scripts/ccomp.lsp"
rm -f "$DESTDIR/lib/build_scripts/mkbytes.red"
rm -f "$DESTDIR/lib/build_scripts/opcodes.red"

# Removes 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

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

# Deletes snapshot and temporary dir
rm -fr "$DESTDIR"
