#!/bin/sh -e
# creating source tarbal for abacas which comes as plain Perl file
# and needs to be putin to a tarball

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

if ! echo $@ | grep -q upstream-version ; then
    # if called manually run uscan to obtain file and version number
    # VERSION=`dpkg-parsechangelog | awk '/^Version:/ { print $2 }' | sed 's/\([0-9\.]\+\)-[0-9]\+$/\1/'`
    VERSION=`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.]\+\),.*/\1/"`
else
    # If called by uscan
    VERSION=`echo $@ | sed 's?^.*--upstream-version \([0-9.]\+\) .*abacas.*?\1?'`
    if echo "$VERSION" | grep -q "upstream-version" ; then
	echo "Unable to parse version number"
        exit
    fi
fi

#if [ "$VERSION" = "" ] ; then
#    VERSION=`ls ../${PKG}.*.pl | sed "s/.*$PKG\.\(.*\)\.pl/\1/"`
#fi

mkdir -p ../tarballs/${PKG}-${VERSION}
cd ../tarballs

# Rename perl file (without .pl suffix) and fix perl path
sed -e '1s?/usr/local/bin/perl?/usr/bin/perl?' \
    -e "s/^${PKG}.pl/${PKG}/" \
    ../${PKG}.${VERSION}.pl > ${PKG}-${VERSION}/${PKG}
touch -r ../${PKG}.${VERSION}.pl ${PKG}-${VERSION}/${PKG}
rm -f ../${PKG}.${VERSION}.pl

cd ${PKG}-${VERSION}
wget -q -N http://abacas.sourceforge.net/Manual.html
sed -i -e 's?index.html">Home?http://abacas.sourceforge.net/&?' \
       -e 's?documentation.html">Documentation?http://abacas.sourceforge.net/&?' \
       -e 's/perl abacas\.pl/abacas/' \
       -e 's/abacas\.pl/abacas/' \
       Manual.html
wget -q -N http://abacas.sourceforge.net/style.css
cd ..

GZIP="--best --no-name" tar -czf "$PKG"_"$VERSION".orig.tar.gz "$PKG"-"$VERSION"
rm -rf "$PKG"-"$VERSION"
