#!/bin/sh -e

# Remark: A new uscan that enables easier handling of removing files can be
#         obtained via
#   git clone git://tille@git.debian.org/git/users/tille/devscripts.git
#         and then copy scripts/uscan.pl as uscan at the beginning of your PATH
if uscan --help | grep -q -- --repack-compression ; then
    echo "Use new enhanced uscan"
    uscan --verbose --force-download --repack-compression xz
    exit
fi

# Upstream provides source in ZIP file so we have to repack anyway and
# thus it seems reasonable to remove some binary cruft

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

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

UVERSION=${ORIGNAME}`echo ${DVERSION} | sed 's/\.//'`
UPSTREAMZIP=${UVERSION}-src.zip

UPSTREAMDIR=source

cd ..
mkdir -p tarballs

if [ ! -f "$UPSTREAMZIP" ] ; then
    wget -q http://imagej.nih.gov/ij/download/src/"$UPSTREAMZIP"
fi
cd tarballs
unzip -q ../"$UPSTREAMZIP"

cd "$UPSTREAMDIR"
# remove hidden binary files
rm -rf .FBC*
# remove gdb history
rm -f .gdb_history

cd ..
mv "$UPSTREAMDIR" "$NAME"-"$DVERSION"
GZIP="--best --no-name" tar --owner=root --group=root --mode=a+rX -caf "$NAME"_"$DVERSION".orig.tar.xz "$NAME"-"$DVERSION"
rm -rf "$NAME"-"$DVERSION"
