#!/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`
cleanfile=`dirname $0`/dfsg.remove

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
while read rmpattern
do
    rm -rf $UPNAME-$UPVER.orig/$rmpattern
done < $cleanfile

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
