#!/bin/sh
# get source for beast-mcmc from SVN because there is no source tarball distribution

set -e
NAME=`dpkg-parsechangelog | awk '/^Source/ { print $2 }'`
ORIGNAME=beast

if ! echo $@ | grep -q upstream-version ; then
    VERSION=`dpkg-parsechangelog | awk '/^Version:/ { print $2 }' | sed 's/\([0-9\.]\+\)-[0-9]\+$/\1/'`
else
    VERSION=`echo $@ | sed "s?^.*--upstream-version \([0-9.]\+\) .*${ORIGNAME}_release.*?\1?"`
    if echo "$VERSION" | grep -q "upstream-version" ; then
        echo "Unable to parse version number"
        exit
    fi
fi

SVNTAG=`echo ${VERSION} | sed 's/\./_/g'`
rm -f ../${ORIGNAME}_release_${SVNTAG}
RELEASE=${ORIGNAME}_release_${SVNTAG}
TARDIR=${NAME}-${VERSION}

mkdir -p ../tarballs
cd ../tarballs
# svn export conserves time stamps of the files, checkout does not
LC_ALL=C svn export http://${NAME}.googlecode.com/svn/tags/${RELEASE} ${TARDIR} >/dev/null 2>/dev/null

# remove jars which are provided as binaries but are not directly needed to build FigTree
for jar in \
            JRI.jar \
            beagle.jar \
            colt.jar \
            commons-math-*.jar \
            figtreepanel.jar \
            itext-1.4.5.jar \
            jam.jar \
            jdom.jar \
            jebl.jar \
            junit-4.4.jar \
            libjri.jnilib \
            mpj.jar \
            mtj.jar \
            options.jar \
            org.boehn.kmlframework_20090320.jar \
        ; do
    rm -rf ${TARDIR}/lib/$jar
done

# No source available for phylogeography
find ${TARDIR} -mindepth 1 -maxdepth 1 -name "*phylogeography*" | xargs rm -rf

rm -rf ${TARDIR}/release/Mac ${TARDIR}/release/Windows ${TARDIR}/release/Linux/lib/*

# Remove all preprocessed (duplicated!) docs
rm -rf ${TARDIR}/release/common/doc/*
# remove preprocessed docs which can be recreated using LaTeX to make sure that we
# really have the source and to save some disk space in source archive
for pdf in \
            doc/SerialSampleCoalescent.pdf \
            doc/Yule.pdf \
            doc/tutorial/EBSP/ebsp-tut.pdf \
            doc/tutorial/StarBEAST/STARBEAST.pdf \
        ; do
    rm -rf ${TARDIR}/$pdf
done
# ... and every *.pdf named "Practical_<something>"
find ${TARDIR}/doc -name "Practical_*.pdf" -delete
# There is no point in keeping LaTeX's *.aux files
find ${TARDIR}/doc -name "*.aux" -delete

GZIP="--best --no-name" tar --owner=root --group=root --mode=a+rX -caf "$NAME"_"$VERSION".orig.tar.xz "${TARDIR}"
rm -rf "${NAME}"-"$VERSION"
