#!/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+dfsg"
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"
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

## Remove sourceless minified JavaScript, CSS, fonts, Flash, and Silverlight
rm -vr $UP_BASE/3rdparty/timepicker/css/include
rm -vr $UP_BASE/3rdparty/phpdocx/pdf/tcpdf/fonts/free*
rm -v  $UP_BASE/3rdparty/dompdf/lib/fonts/*.ttf
rm -v  $UP_BASE/apps/documents/css/fonts/*.ttf
rm -v  $UP_BASE/apps/documents/css/fonts/wqy-microhei.ttc
rm -v  $UP_BASE/apps/files_videoviewer/js/flashmediaelement.swf
rm -v  $UP_BASE/apps/files_videoviewer/js/silverlightmediaelement.xap
rm -v  $UP_BASE/core/js/jquery-1.10.0.min.js
rm -v  $UP_BASE/core/doc/*/_static/bootstrap.css
rm -v  $UP_BASE/core/doc/*/_static/bootstrap.js
rm -v  $UP_BASE/core/doc/*/_static/bootstrap-responsive.css
rm -v  $UP_BASE/core/doc/*/_static/jquery.js
rm -v  $UP_BASE/core/doc/*/_static/underscore.js
rm -v  $UP_BASE/core/doc/*/searchindex.js

# following contain incompatible license with Debian
rm -vr $UP_BASE/3rdparty/Console
rm -v  $UP_BASE/3rdparty/phpdocx/pdf/tcpdf/fonts/utils/*.dll
rm -vr $UP_BASE/3rdparty/fontawesome/docs
rm -v  $UP_BASE/3rdparty/symfony/console/Symfony/Component/Console/Resources/bin/hiddeninput.exe
rm -v  $UP_BASE/apps/contacts/js/jshint.js
rm -vr $UP_BASE/apps/files_encryption/3rdparty/Crypt_Blowfish
rm -v  $UP_BASE/apps/files_texteditor/js/vendor/ace/src-noconflict/worker-*
rm -v  $UP_BASE/core/doc/admin/_images/10000000000004CA000002B52116BE0C.png
rm -v  $UP_BASE/core/doc/admin/_images/100000000000044C000002B0B421E27E.png
## 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!"
