#!/bin/sh

set -ex

PKGDIR="$PWD"

# ignore <path> and rely on ../ being the path to the orig.tar.xz
# using source package name $SPKG from debian/changelog
# This makes it more robust for newer uupdate in future
SPKG=$(dpkg-parsechangelog -SSource)

#NEW_VERSION=$(dpkg-parsechangelog -SVersion | sed 's/\-[0-9]*$//')

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

new_package="${SPKG}-${NEW_VERSION}"

clean () {
    rm -rf ../${new_package} ../${SPKG}.tmp.tar.gz
}

trap clean EXIT

cd ..
# Remove original download since its lacking DALIGNER and DAZZ_DB
rm -f ${SPKG}-${NEW_VERSION}.tar.[gx]z

# since daligner und dazz_db are needed and are only provided
# as submodules and this old code seems to be really needed
#   see https://lists.debian.org/debian-med/2018/07/msg00088.html
echo "Cloning ${SPKG} version ${NEW_VERSION}"
git clone \
    https://github.com/PacificBiosciences/pbdagcon.git $new_package

cd $new_package
# Add "|| true" since it returns:
#  Fetched in submodule path 'blasr_libcpp', but it did not contain 9b4faa3efa2d59484af3c3562a3af6ce421e0294. Direct fetching of that commit failed.
#  makefile:22: recipe for target 'update-submodule' failed
make update-submodule || true
# debug
# ls -l DALIGNER
# ls -l DAZZ_DB
rm -rf blasr_libcpp
find -name ".git*" | xargs rm -rf
cd $PKGDIR

tar -czf ../${SPKG}.tmp.tar.gz ../${new_package}
mk-origtargz --compression xz --repack --version ${NEW_VERSION}+ds ../${SPKG}.tmp.tar.gz
