#!/bin/sh -e

# Its obviously not reliable to do the versioning based on the date given in file
#   http://www.netlib.org/f2c/src/version.c
#
# This script downloads the ZIP archive and defines the Version as the time stamp
# of the youngest file inside the archive

COMPRESS=xz

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

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

wget --quiet -N http://www.maths.otago.ac.nz/~dbryant/software/PhiPack.tar.gz

tar xaf PhiPack.tar.gz
rm -f ._PhiPack
mv PhiPack ${NAME}
cd ${NAME}

# find youngest file name:
#    find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | cut -f2- -d" "
VERSION=0.0.`find . -type f -printf '%T@ %p\n' | sort -n | tail -1 | sed 's/ .*//' | gawk '{print strftime("%Y%m%d", $0)}'`
find . -name "._*" -delete
find . -name "*~" -delete
find . -name ".DS_Store" -delete
find . -name "_notes" -type d | xargs -r rm -rf

if [ "$OVERSION" = "$VERSION" ] ; then
  echo "No new version of $NAME available (VERSION=${VERSION})."
  exit 0
fi

find . -type f -exec chmod -x \{\} \;

cd ..

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