#!/bin/sh
# if you need to repack for whatever reason you can
# use this script via uscan or directly
#
# FIXME: currently the code is not conform to Debian Policy
#        http://www.debian.org/doc/debian-policy/ch-source.html
#        "get-orig-source (optional)"
#        This target may be invoked in any directory, ...
# --> currently it is assumed the script is called in the
#     source directory featuring the debian/ dir

COMPRESS=xz

NAME=`dpkg-parsechangelog | awk '/^Source/ { print $2 }'`
COPYRIGHT=$(pwd)/debian/copyright

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

set -e

## NO tags no branches
SVNURI="svn://svn.code.sf.net/p/brig/code/"

TARDIR=${NAME}-${VERSION}

mkdir -p ../tarballs
cd ../tarballs
# svn export conserves time stamps of the files, checkout does not
rm -rf ${NAME}-code
LC_ALL=C svn --quiet export ${SVNURI} ${NAME}-code
unzip -q ../BRIG-${VERSION}-dist.zip
mv BRIG-${VERSION}-dist ${TARDIR}
cd ${TARDIR}
# Remove according to "Files-Excluded"
# Its a bit tricky since '*' needs to be escaped ...
for excl in $(grep "^Files-Excluded" ${COPYRIGHT} | sed -e 's/^Files-Excluded: */ /' -e 's/ \*/ \\*/g') ; do find . -path "$(echo $excl | sed 's/^\\//')" | xargs rm -rf ; done
# copy Java source from SVN
mv ../${NAME}-code/BRIG/src .
# Cherry pick from SVN content - no idea what principle upstream followed when creating download archive
mv ../${NAME}-code/BRIG/HELP HELP
mv ../${NAME}-code/BRIG/README.txt README_devel.txt
mv ../${NAME}-code/BRIG/[a-d]*.xml .
mv ../${NAME}-code/BRIG/manifest* .
mv ../${NAME}-code/BRIG/*.fasta .
mv ../${NAME}-code/BRIG/proteins.txt .
mv ../${NAME}-code/BRIG/nbproject .
chmod 644 proteins.txt src/brig/*
rm -rf ../${NAME}-code
cd ..

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