#!/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="$2debian"
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 stuff
rm -vfr $UP_BASE/3rdparty/timepicker/css/include
rm -vfr $UP_BASE/core/js/jquery-1.7.2.min.js
rm -vfr $UP_BASE/core/js/jquery-ui-1.8.16.custom.min.js
# following two have incompatible license with Debian
rm -vfr $UP_BASE/3rdparty/Console/Getopt.php
rm -vfr $UP_BASE/3rdparty/Crypt_Blowfish
# remove expermental app: external storage
rm -vfr $UP_BASE/apps/files_external
rm -vfr $UP_BASE/3rdparty/smb4php
## End

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

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

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