#!/bin/bash -e
# Repackaging script to be called by Uscan

echo "Repackaging ..."
TMP=$(mktemp -d)
PKG="$(dpkg-parsechangelog|sed 's/^Source: //p;d')_$2+dfsg.orig"
TARGETPATH=$(realpath ..)

echo "Extracting tarball ..."
tar xzf "$3" -C "$TMP"
pushd "$TMP"

NOMACS=$(realpath nomacs-*)
echo $NOMACS

echo "Removing unwanted stuff ..."
rm -rf $NOMACS/exiv2-* 
rm -rf $NOMACS/expat
rm -rf $NOMACS/herqq
rm -rf $NOMACS/installer
rm -rf $NOMACS/LibRaw-*
rm -rf $NOMACS/zlib-*
rm -rf $NOMACS/ImageLounge/3rdparty/libwebp
rm -rf $NOMACS/ImageLounge/3rdparty/quazip-0.7

rm -f  $NOMACS/.gitignore
rm -f  $NOMACS/.travis.yml
rm -f  $NOMACS/README.md

echo "Copy ImageLounge-Files to nomacs-* ..."
mv $NOMACS/ImageLounge/* $NOMACS

echo "Remove the now empty ImageLounge directory ..."
rm -rf $NOMACS/ImageLounge

echo "Create a valid root license ..."

cp -f  $NOMACS/Readme/LICENSE.GPLv3 $NOMACS/COPYRIGHT

echo "Remove non-free lena pics ..."
find . -name lena*.jpg -delete

echo "Creating dfsg tarball ..."
tar cfvJ "$PKG.tar.xz" nomacs-*

echo "Repackaged tarball $PKG.tar.xz created in $TMP ..."

popd

echo "Remove the linked orgig.tar ..."
rm -f "$3"

echo "Copy the dfsg-tar to it's designated place ..."
cp "$TMP/$PKG.tar.xz" "$TARGETPATH"

