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

set -e
set -u

VER="$2"
FILE="$3"
PKG=`dpkg-parsechangelog|grep ^Source:|sed 's/^Source: //'`

REPACK_DIR="$PKG-$VER.orig" # DevRef § 6.7.8.2

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"
unzip "$FILE" -d "$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

## Remove non-DFSG compliant material (Old version under PHP-2.02)
rm -vr $UP_BASE/plugins-dist/safehtml/lib/safehtml/classes/HTMLSax3
rm -v  $UP_BASE/plugins-dist/safehtml/lib/safehtml/classes/HTMLSax3.php
## Sourceless JavaScript
rm -v  $UP_BASE/plugins-dist/msie_compat/javascript/blank.gif
rm -v  $UP_BASE/plugins-dist/msie_compat/javascript/IE7.js
rm -v  $UP_BASE/plugins-dist/msie_compat/javascript/ie7-recalc.js
rm -v  $UP_BASE/plugins-dist/msie_compat/javascript/ie7-squish.js
rm -v  $UP_BASE/plugins-dist/msie_compat/javascript/IE8.js
rm -v  $UP_BASE/plugins-dist/msie_compat/javascript/IE9.js
## End

mv "$UP_BASE" "$DIR/$REPACK_DIR"

# Using a pipe hides tar errors!
tar cfC "$DIR/repacked.tar" "$DIR" "$REPACK_DIR"
xz < "$DIR/repacked.tar" > "$DIR/repacked.tar.xz"
RESULTING_FILE="$(dirname $FILE)/${PKG}_${VER}.orig.tar.xz"
mv "$DIR/repacked.tar.xz" "$RESULTING_FILE"
rm -f "$FILE"

echo "*** $FILE repackaged"
echo "*** Please note that the upstream version must be $VER since we are repackaging the tarball!"
