#!/bin/sh -e
# Repackaging script to be called by Uscan
# http://www.danielstender.com/blog/uscan-repaketierung.html

DEBVERSIONNUM=$2
UVERSION=`echo $DEBVERSIONNUM|sed 's/\.\([a-z]\)$/\1/'`
PATHTOUTARBALL=$3
BUILD_DATE=`dpkg-parsechangelog | sed -n -e 's/^Date: //p'`

DEBVERSION=$DEBVERSIONNUM+dfsg1

echo "Repackaging ..."
TMP=`mktemp -d`
NAME="`dpkg-parsechangelog|sed 's/^Source: //p;d'`"
PKG="${NAME}_${DEBVERSION}.orig"
#echo "|$NAME|$DEBVERSION|$UVERSION|$PKG|"

export DEBVERSION UVERSION PATHTOUTARBALL TMP NAME PKG

echo "Extracting tarball ..."
tar xzf "$PATHTOUTARBALL" -C "$TMP"
( cd "$TMP"
mv src-mgen-$UVERSION mgen_$DEBVERSION

echo "Removing unwanted stuff ..."
find mgen_$DEBVERSION -name '*.pdf' -print0 | xargs -0r rm
find mgen_$DEBVERSION -name '*.xml' -print0 | xargs -0r rm
find mgen_$DEBVERSION -name '*.xmi' -print0 | xargs -0r rm
# duplicate files
for i in mgen_$DEBVERSION/doc/resources/* ; do
  rm -f mgen_$DEBVERSION/doc/`basename $i`
done
# remove unneeded files with unclear licenses
rm -rf mgen_$DEBVERSION/makefiles/win*
rm -rf mgen_$DEBVERSION/src/sim
rm -rf mgen_$DEBVERSION/protolib/makefiles/win*
rm -rf mgen_$DEBVERSION/protolib/src/win*
rm -rf mgen_$DEBVERSION/protolib/src/sim
rm -rf mgen_$DEBVERSION/protolib/makefiles/java
rm -rf mgen_$DEBVERSION/protolib/src/java
rm -rf mgen_$DEBVERSION/protolib/waf
rm -rf mgen_$DEBVERSION/protolib/waf.bat
rm -rf mgen_$DEBVERSION/protolib/wscript

echo "Creating dfsg tarball in $TMP..."

# correct weird permissions
find mgen_$DEBVERSION/ -type f -print0 | xargs -0r chmod 644
find mgen_$DEBVERSION/ -type d -print0 | xargs -0r chmod 755

tar --mtime="$BUILD_DATE" -cf "$PKG.tar" mgen_$DEBVERSION/
xz -9 < "$PKG.tar" > "$PKG.tar.xz"
rm "$PKG.tar" )

echo "Moving tarball to ../ and Cleaning up..."
mv $TMP/$PKG.tar.xz ../
rm -rf $TMP/

echo "Repackaged tarball can now be found at ../$PKG.tar.xz"
