#!/bin/sh -f

# Upstream produces srsly broken releases. Until that is fixed, this script
# will be used. It downloads the original tarball, removes prebuild binary,
# assings a proper version tag and then repacks.

# FIXME: currently the code is not conform to Debian Policy
#        http://www.debian.org/doc/debian-policy/ch-source.html
#        "get-orig-source (optional)"
#        This target may be invoked in any directory, ...
# --> currently it is assumed the script is called in the
#     source directory featuring the debian/ dir

COMPRESS=xz

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

if ! echo $@ | grep -q upstream-version ; then
    VERSION=`dpkg-parsechangelog | awk '/^Version:/ { print $2 }' | sed 's/\([0-9\.]\+\)-[0-9]\+$/\1/'`
else
    VERSION=`echo $@ | sed "s?^.*--upstream-version \([0-9.]\+\) .*${NAME}.*?\1?"`
    if echo "$VERSION" | grep -q "upstream-version" ; then
        echo "Unable to parse version number"
        exit
    fi
fi

SOURCE_URL=`awk '/^Source/ {print $2}' cat debian/copyright`
EXCLUDE=`grep 'Files-Excluded' debian/copyright | cut -d' ' -f2-`
UPSTREAMTARBALL="spaced-protein_dna.tar.gz"


wget SOURCE_URL

mkdir -p ../tarballs
rm -rf ../tarballs/*

OLDPWD=$PWD

cd ../tarballs
mkdir "spaced-legacy"
tar -xaf $OLDPWD/${UPSTREAMTARBALL} -C spaced-legacy

# Fix upstreams non-Gnu naming scheme
TARDIR=${NAME}-${VERSION}
UPSTREAMTARDIR=`find . -mindepth 1 -maxdepth 1 -type d`
if [ "${UPSTREAMTARDIR}" != "${TARDIR}" ] ; then
    mv "${UPSTREAMTARDIR}" "${TARDIR}"
fi

# Remove useless binaries
(cd "${TARDIR}" && rm -f ${EXCLUDE})

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

mv "$NAME"_"$VERSION".orig.tar.${COMPRESS} ..
