#!/bin/sh
# get source for king and strip binary JARs

set -e
NAME=`dpkg-parsechangelog | awk '/^Source/ { print $2 }'`

if ! echo $@ | grep -q upstream-version ; then
    VERSION=`dpkg-parsechangelog | awk '/^Version:/ { print $2 }' | sed 's/\([0-9\.]\+\)-[0-9]\+$/\1/'`
else
    VERSION=`echo $@ | sed "s?^.*--upstream-version \([0-9.]\+\) .*${name}.*?\1?"`
    if echo "$VERSION" | grep -q "upstream-version" ; then
        echo "Unable to parse version number"
        exit
    fi
fi

TARDIR=${NAME}-${VERSION}

mkdir -p ../tarballs/$TARDIR
cd ../tarballs/$TARDIR
unzip -q ../../${NAME}.${VERSION}.src.zip

# Remove useless JAR and CLASS files
find . -name "*.jar" -delete
find . -name "*.class" -delete

# Remove javadocs which could be easily recreated in the build
# process using
#  ant -buildfile king/build.xml dist-src
# Please note that you need to activate the quilt patch
#  debian/patches/delete_mac_specific_file.patch
# in the series file to do so
rm -rf javadocs

# Remove useless dirs
rm -rf lib
find . -name .xvpics | xargs rm -rf

# Clean up binary installer code
rm -rf king-*-src/installer/win* king-*-src/installer/linux*

# once we are cleaning up the tarball anyway it makes sense to remove useless file duplicates
rm -rf extratools-*-src/doc/work/tools-manual.pdf \
       king-*-src/doc/work/king-manual.pdf \
       king-*-src/doc/work/format-kinemage.pdf
rm -rf king-*-src/installer/kingicon-orig.png \
       king-*-src/installer/kingicon[12346][02468].png \
       king-*-src/installer/kingicon[13][26].gif

# there is only no point in keeping copies of old versions of the code
rm -rf king-*-src/1.x_src

# as king-*-src/BUILD.html suggests you should de-versionify the single components
# by copying the directories to generic names.  This turns out to be a burden inside
# debian/rules and thus we simply do it here in the orig-tar generation step
for dir in `find . -mindepth 1 -maxdepth 1 -type d -name "[a-z]*-*-src"` ; do
  ln -s $dir `echo $dir | sed 's/-[^-]\+-src$//'`
done

cd ..
GZIP="--best --no-name" tar --owner=root --group=root --mode=a+rX -czf "$NAME"_"$VERSION".orig.tar.gz "${TARDIR}"
rm -rf "$TARDIR"
