#!/bin/sh
# unpack spread tarball to get rid of several binaries

set -e
NAME=`dpkg-parsechangelog | awk '/^Source/ { print $2 }'`
UPSTREAMNAME=`echo $NAME | sed 's/phy-//'`

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.]\+\) .*${UPSTREAMNAME}.*?\1?"`
    if echo "$VERSION" | grep -q "upstream-version" ; then
        echo "Unable to parse version number"
        exit
    fi
fi

TARDIR=${UPSTREAMNAME}-${VERSION}
mkdir -p ../tarballs
cd ../tarballs
# need to clean up the tarballs dir first because upstream tarball might
# contain a directory with unpredictable name
rm -rf *
mv ../${TARDIR}.tar.gz .
tar -xzf ${TARDIR}.tar.gz

UPSTREAMTARDIR=`find . -mindepth 1 -maxdepth 1 -type d`
if [ "${UPSTREAMTARDIR}" != "${TARDIR}" ] ; then
    mv "${UPSTREAMTARDIR}" "${TARDIR}"
fi

# Remove useless binaries
rm -rf ${TARDIR}/release/Mac
rm -rf ${TARDIR}/release/Windows
rm -rf ${TARDIR}/release/tools

# Remove debian packaged jars
rm -rf ${TARDIR}/lib/*

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