#!/bin/sh -e
# Upstream provides source in ZIP file so we have to repack anyway and
# thus it seems reasonable to remove some binary cruft

NAME=imagej
# Obtain upstream version number from changelog file
# DVERSION=`grep "^${NAME} *(.\+)" debian/changelog | head -n 1 | sed "s/^${NAME} \+(\([^-]\+\)-[0-9]*) .*/\1/"`
# Find out latest upstream version
DVERSION=`uscan --verbose --force-download | \
    grep "Newest version on remote site is .* local version is .*" | \
    head -n 1 | \
    sed "s/Newest version on remote site is \([-0-9.]\+[a-z]*\),.*/\1/"`

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

UPSTREAMDIR=source

mkdir -p ../tarballs
cd ../tarballs

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

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 -czf "$NAME"_"$DVERSION".orig.tar.gz "$NAME"-"$DVERSION"
rm -rf "$NAME"-"$DVERSION"
