#!/bin/bash

DEHS=`( uscan --dehs )`

URL=`echo $DEHS | xsltproc debian/uscan-url.xslt -`
VERSION=`echo $DEHS | xsltproc debian/uscan-upstream-version.xslt -`

DEBIAN_SOURCE_VERSION="$VERSION+ds1"

DESTDIR=$PWD/..
SOURCEFILE=$DESTDIR/lucene-$VERSION-src.tar.gz
SIGFILE=$DESTDIR/lucene-$VERSION-src.tar.gz.asc
SOURCETAR=$DESTDIR/lucene2_$DEBIAN_SOURCE_VERSION.orig.tar

KEYURL="http://www.apache.org/dist/lucene/java/KEYS"
KEYFILE="debian/KEYS"
KEYRING="debian/lucene-keyring.gpg"

# Download source tarball and signature file
if [ ! -r "$SOURCEFILE" ]; then
  wget "$URL" -O $SOURCEFILE
fi

wget "$URL.asc" -O $SIGFILE

# If necessary, recreate keyring used for signing
# Only do this if the keyring is not yet downloaded
if [ ! -r $KEYFILE ]; then
    wget "$KEYURL" -O "$KEYFILE"
fi

if [ ! -r $KEYRING ]; then
    touch $KEYRING
    gpg --no-default-keyring --primary-keyring $KEYRING --import $KEYFILE
fi

# Check signature
gpgv --quiet --keyring $KEYRING $SIGFILE $SOURCEFILE

echo "Check whether the archive has been signed by Mark Robert Miller (CODE SIGNING KEY) <markrmiller@apache.org>, key ID EB0199F8"

# Repackage upstream source file without the third party jars
TEMPDIR=`mktemp -d`
echo "Unpacking into tempdir $TEMPDIR..."
tar xzf $SOURCEFILE -C $TEMPDIR

echo "Removing third party jars..."
find $TEMPDIR -name \*.jar -exec rm {} \;

echo "Removing pre-generated javacc output files..."
# Some generated files are excepted because they are not properly generated by
# the build system
fgrep -lR "Generated By:JavaCC:" $TEMPDIR | grep -v "analysis/standard/ParseException.java\|precedence\|surround" | xargs -n5 rm

echo "Packing new orig source tarball $SOURCETAR..."
rm -f $SOURCETAR $SOURCETAR.gz
cd $TEMPDIR
tar cf $SOURCETAR *
gzip -9 $SOURCETAR
cd $DESTDIR

echo "Removing tempdir..."
rm -rf "$TEMPDIR"

