#!/bin/sh

set -e

VER="$2"-dfsg
FILE="$3"
PKG=`dpkg-parsechangelog|grep ^Source:|sed 's/^Source: //'`
UPSTREAM_NAME=`echo $FILE | sed 's/\.\.\///'` 
SRC_NAME=`basename $UPSTREAM_NAME .7z`
REPACK_DIR="$SRC_NAME"-dfsg
DIR=`mktemp -d ./tmpRepackXXXXXX`
trap "rm -rf \"$DIR\"" QUIT INT EXIT
# Create an extra directory to cope with rootless tarballs
UP_BASE="$DIR/unpack/$SRC_NAME"
mkdir -p "$UP_BASE"
7z e "$FILE" -o"$UP_BASE" && rm $UP_BASE/*.exe && rmdir YozFont

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!
FILE="../${PKG}_${VER}.tar.xz"
tar cfC "$DIR/repacked.tar" "$DIR" "$REPACK_DIR"
xz -9e "$DIR/repacked.tar" && mv "$DIR/repacked.tar.xz" "$FILE"
echo "*** $FILE repackaged"

uupdate -u $FILE -v $VER
