#!/bin/sh
# Repackage upstream source to xz --best
set -e
set -u

VER="$2"
FILE="$3"
PKG=`dpkg-parsechangelog|grep ^Source:|sed 's/^Source: //'`
REPACK_DIR="$PKG-$VER.orig"
echo -e "\nRepackaging $FILE\n"
DIR=`mktemp -d ./tmpRepackXXXXXX`
trap "rm -rf \"$DIR\"" QUIT INT EXIT
# Create an extra directory to cope with rootless tarballs
UP_BASE="$DIR/unpack"
mkdir "$UP_BASE"
tar xJf "$FILE" -C "$UP_BASE"

if [ `ls -1 "$UP_BASE" | wc -l` -eq 1 ]; then
        # Tarball does contain a root directory
        UP_BASE="$UP_BASE/`ls -1 "$UP_BASE"`"
fi
mv "$UP_BASE" "$DIR/$REPACK_DIR"
# Using a pipe hides tar errors!
tar cfC "$DIR/repacked.tar" "$DIR" "$REPACK_DIR"
xz --best  < "$DIR/repacked.tar" > "$DIR/repacked.tar.xz"
FILE="../${PKG}_${VER}.orig.tar.xz"
mv "$DIR/repacked.tar.xz" "$FILE"
echo "*** $FILE repackaged"
