#!/bin/sh
set -e

# Usage: set the following ENVVARs
#   UPNAME      upstream source name
#   UPVER       upstream version
#   SVNURL      URL to svn repo
#   SVNREV      svn revision 

workdir=`pwd`

if ! which svn >/dev/null
then
        echo "Error: subversion must be installed for this to work" >&2
        exit 1
fi

for reqvar in UPNAME UPVER SVNURL SVNREV
do
    if [ -z "`eval echo '$'$reqvar`" ]
    then
            echo "Error: \$$reqvar is not set" >&2
            exit 1
    fi
done

tmpdir=`mktemp -d`
cd $tmpdir

if ! svn export -q -r $SVNREV $SVNURL $UPNAME-$UPVER.orig
then
    rm -rf $tmpdir
    exit 1
fi

# Clean up a bit
cd $UPNAME-$UPVER.orig
rm -rf .checkstyle .project .pydevproject .settings python_keyczar.egg-info
cd ..

if ! GZIP="-9" tar --owner=root --group=root --mode=a+rX \
    -czf orig.tar.gz $UPNAME-$UPVER.orig
then
    rm -rf $tmpdir
    exit 1
else
    mv orig.tar.gz $workdir/${UPNAME}_${UPVER}+svn${SVNREV}.orig.tar.gz
fi

rm -rf $tmpdir
