#!/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}' debian/copyright`
EXCLUDE=`grep 'Files-Excluded' debian/copyright | cut -d' ' -f2-`
UPSTREAMTARBALL=`echo $SOURCE_URL | sed 's#^.*/\([^/]\+\)#\1#'`


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

cd ../tarballs
rm -rf ${NAME}
wget -q -N $SOURCE_URL

set -x
tar -xaf ${UPSTREAMTARBALL}

# Remove useless binaries
UPSTREAMTARDIR=`find . -mindepth 1 -maxdepth 1 -type d -name "${NAME}*"`
cd "${UPSTREAMTARDIR}"
rm -f ${EXCLUDE}
# obtain version from file variance.h
VERSION=`grep '@version: [0-9][0-9.]\+ [0-9/]\+' $(find . -name variance.h) | sed 's#.*@version: \([0-9][0-9.]\+\) \([0-9]\+\)/\([0-9]\+\)#\1-\3\2#'`+dfsg
cd ..

# Fix upstreams non-Gnu naming scheme
TARDIR=${NAME}-${VERSION}
if [ "${UPSTREAMTARDIR}" != "${TARDIR}" ] ; then
    mv "${UPSTREAMTARDIR}" "${TARDIR}"
fi

# 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} ..
