#!/bin/sh -e

COMPRESS=xz

ONAME=cgview_comparison_tool

NAME=`dpkg-parsechangelog | awk '/^Source/ { print $2 }'`
OVERSION=`dpkg-parsechangelog | awk '/^Version:/ { print $2 }' | sed -e 's/+dfsg//' -e 's/-[0-9]\+$//'`

COPYRIGHT=$(pwd)/debian/copyright

mkdir -p ../tarballs
cd ../tarballs
# need to clean up the tarballs dir first because upstream tarball might
# contain a directory with unpredictable name
rm -rf ${ONAME} ${NAME}*

# wget fails for strange reasons
# wget http://www.ualberta.ca/~stothard/downloads/${ONAME}.zip
curl https://sites.ualberta.ca/~stothard/downloads/${ONAME}.zip --output ${ONAME}.zip $zflag
unzip -q ${ONAME}.zip
cd ${ONAME}

# find youngest file name:
# VERSION=0.0.`find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | sed 's/ .*//' | gawk '{print strftime("%Y%m%d", $0)}'`
VERSION=`ls RELEASE* | head -n1 | sed -e 's/^RELEASE-//' -e 's/_//g'`
if [ "$OVERSION" = "$VERSION" ] ; then
  echo "No new version of $NAME available (VERSION=${VERSION})."
  exit 0
fi
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

cd ..
TARDIR=${NAME}-${VERSION}+dfsg
mv ${ONAME} ${TARDIR}
# Remove according to "Files-Excluded"
# Its a bit tricky since '*' needs to be escaped ...

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