#!/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

FILE=$3
PKG=`dpkg-parsechangelog|grep ^Source:|sed 's/^Source: //'`
VER=$2
#VER=`dpkg-parsechangelog|grep ^Version:|sed 's/^Version: //; s/+dfsg-[^-]\+$//'`

printf "\nRepackaging $FILE\n"

DIR=`mktemp -d ./tmpRepackXXXXXX`
trap "rm -rf $DIR" QUIT INT EXIT

mkdir $DIR/$PKG-$VER
unzip $FILE -d $DIR/$PKG-$VER

REPACK=${PKG}_$VER.orig.tar.gz

UP_DIR=$PKG-$VER

(
    set -e
    set -u

    cd $DIR

    # Files without proper copyright notices and unused
    rm -vrf $UP_DIR/src/SSO
    rm -vrf $UP_DIR/src/XA
    #rm -vrf $UP_DIR/src/tools
    rm -vf $UP_DIR/src/test/net/sourceforge/jtds/test/{AsTest.java,CSUnitTest.java,DatabaseTestCase.java,JDBC3Test.java,NtlmAuthTest.java,SAfeTest.java,SanityTest.java,Tds5Test.java,TestBase.java,TimestampTest.java,UpdateTest.java}
    rm -vf $UP_DIR/src/tools/net/sourceforge/jtds/tools/{PacketLogger.java,SQLProxy.java,SqlForwarder.java}

#src/main/net/sourceforge/jtds/util/DESEngine.java

    # Third party libraries inclued without any attribution
    rm -vrf $UP_DIR/lib

    REPACK_DIR="$PKG-$VER.orig"
    mv $UP_DIR $REPACK_DIR
    tar -c $REPACK_DIR | gzip -9 > $REPACK
)

#mv $DIR/$REPACK $FILE
mv $DIR/$REPACK `dirname $FILE`
rm -f $FILE

echo "*** $FILE repackaged"
