#!/bin/sh -e

# Upstream just delivers an unversioned tarball
# This script will turn this into a versioned source tarball
# based on the date of the youngest file inside the tarball

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

COMPRESS=xz

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

wget --quiet -N http://www.ampl.com/netlib/ampl/solvers.tgz

tar xaf solvers.tgz
mv solvers ${NAME}
cd ${NAME}

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

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

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}
