#!/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

# For an example how to fetch source from sourceforge SVN see
#   git://anonscm.debian.org/debian-med/kmer-tools.git

COMPRESS=xz

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

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

VERSION=`echo $VERSION | sed 's/-[0-9]$//'`
ORIGVERSION=`echo $VERSION | sed 's/+d.*//'`

BUILDDEPS="bowtie2"
missingdepends=`dpkg -l ${BUILDDEPS} | \
    grep -v -e "^ii" -e "^|" -e "^++" -e "^ " -e "^..[^[:space:]]" | \
    sed 's/^[a-z][a-z][[:space:]]\+\([^[:space:]]\+\)[[:space:]]\+.*/\1/'`

if [ "$missingdepends" != "" ] ; then
    echo "Please install the following packages to rebuild the upstream source tarball:"
    echo $missingdepends
    exit -1
fi

TARDIR=${NAME}-${VERSION}
mkdir -p ../tarballs
cd ../tarballs
# need to clean up the tarballs dir first because upstream tarball might
# contain a directory with unpredictable name
find . -type d | xargs -r rm -rf 2>/dev/null || true
rm -f "$NAME"_"$VERSION".orig.tar.${COMPRESS}
tar xaf ../${ORIGVERSION}.tar.bz2
mv biobakery-metaphlan2-* ${TARDIR}
cd ${TARDIR}

find . -type f ! -name "*.bt2" -a ! -name "*.txt" -delete
find . -type d -empty | xargs -r rm -rf
cd db_v20
bowtie2-inspect mpa_v20_m200 > markers.fasta
md5sum *.bt2 | sort > bt2.md5
rm *.bt2
cd ../..

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