#!/bin/sh
# Repackage upstream source to exclude VCS files
# should be called as "repack.sh --upstream-source <ver> <downloaded file>
# (for example, via uscan)

set -e
set -u

FILE=$3
PKG=`dpkg-parsechangelog|grep ^Source:|sed 's/^Source: //'`
VER=$2
#VER=`dpkg-parsechangelog|grep ^Version:|sed 's/^Version: //; s/+dfsg-[^-]\+$//'`

printf "\nRepackaging $FILE\n"

DIR=`mktemp -d ./tmpRepackXXXXXX`
trap "rm -rf $DIR" QUIT INT EXIT

tar xaf $FILE -C $DIR

REPACK=${PKG}_$VER.orig.tar.gz

(
    set -e
    set -u

    cd $DIR
    UP_DIR=`ls | head -n1`

    rm -vrf $UP_DIR/.hg $UP_DIR/.hgignore

    REPACK_DIR="$PKG-$VER.orig"
    mv $UP_DIR $REPACK_DIR
    tar -c $REPACK_DIR | gzip -9 > $REPACK
)

#mv $DIR/$REPACK $FILE
mv $DIR/$REPACK `dirname $FILE`
rm -f $FILE

echo "*** $FILE repackaged"
