#!/bin/bash
set -e

NAME=eclipse-wtp
VERSION=$2
DEB_VERSION=${VERSION}

TMP_DIR=`mktemp -d`
WORK_DIR=$PWD

VERSION_UNDERSCORE=$(echo $VERSION | sed "s/\./_/g")

moveBundlesFiltered() {
	BUNDLE_DIR=$1
	BUNDLE_FILTER=$2

	BUNDLES=$(find $BUNDLE_DIR -maxdepth 1 -mindepth 1 -type d -name "org.eclipse.*" \
		! -name features ! -name plugins ! -name bundles ! -name docs)

	for bundle in $BUNDLES; do
		if [ "$BUNDLE_FILTER" != "" ] && [ $(basename "$bundle") != "$BUNDLE_FILTER" ]; then
			continue;
		fi
		mv $bundle .
	done
}

cd "$TMP_DIR"

mkdir modules
cd modules

TARBALL=R$VERSION_UNDERSCORE.tar.gz
wget https://github.com/eclipse-wtp-common/webtools.common/archive/refs/tags/$TARBALL
tar -xf $TARBALL
rm -f $TARBALL
MODULE_DIR=webtools.common-R$VERSION_UNDERSCORE
for subdir in . core/bundles xml/bundles features plugins bundles docs; do
        if [ -d $MODULE_DIR/$subdir ]; then
                moveBundlesFiltered "$MODULE_DIR/$subdir" "$MODULE_FILTER"
        fi
done
rm -r $MODULE_DIR

wget https://github.com/eclipse-sourceediting/sourceediting/archive/refs/tags/$TARBALL
tar -xf $TARBALL
rm -f $TARBALL
MODULE_DIR=sourceediting-R$VERSION_UNDERSCORE
for subdir in . core/bundles xml/bundles features plugins bundles docs; do
        if [ -d $MODULE_DIR/$subdir ]; then
                moveBundlesFiltered "$MODULE_DIR/$subdir" "$MODULE_FILTER"
        fi
done
rm -r $MODULE_DIR


cd ..

mkdir ${NAME}-${VERSION}

while read LINE ; do
	echo "Picking $LINE"
	mv modules/$LINE ${NAME}-${VERSION}
done < "$WORK_DIR/debian/wtpbundles"

rm -rf modules

cd ${NAME}-${VERSION}

find -type f -name .cvsignore -delete
find -type f -name .gitignore -delete
find -type f -name Thumbs.db -delete
find -type f -name *.jar -delete

rm -f org.eclipse.wst.xml.core/src/org/eclipse/wst/xml/core/internal/contenttype/XMLHeadTokenizer.java \
      org.eclipse.wst.xml.core/src/org/eclipse/wst/xml/core/internal/parser/XML10Names.java

cd ..

echo "Creating tarball '${NAME}_${DEB_VERSION}.orig.tar.xz'..."
tar -cJf "$WORK_DIR/../${NAME}_${DEB_VERSION}.orig.tar.xz" $NAME-$VERSION

rm -rf "$TMP_DIR"
