#!/bin/bash

DIFFFILE="$1"
if [ ! -f "$DIFFFILE" ]; then
	echo "no valid diff file given"
	exit 1
fi

shift

TEMPDIR=`mktemp -d`

if [ "$?" != "0" -o ! -d "$TEMPDIR" ]; then
	echo "error creating temporary directory"
	exit 1;
fi;

set -e

UPSTREAMDIR=sqwebmail-de-`echo ${DIFFFILE##*/} | perl -pe 's/^.*?([0-9.]+)\..*?$/$1/'`
TARFILE=$UPSTREAMDIR.tar.gz

FUPD="$TEMPDIR/$UPSTREAMDIR"
mkdir $FUPD


cp -v "$DIFFFILE" "$FUPD"
continue=yes
while [ -n "$continue" ]; do
	file=$1
	if [ -f "$file" ]; then
		cp -v $file "$FUPD"
	else 
		continue=""
	fi
	shift || true
done
CPWD=`pwd`
cd $TEMPDIR
#bunzip the patch
cd $UPSTREAMDIR
cd ..
tar czvf $TARFILE $UPSTREAMDIR

cd $CPWD

COPYTO=${DIFFFILE%/*}

if [ ! -d "$COPYTO" ]; then
	COPYTO=.
fi

echo "copying result to $COPYTO"

cp $TEMPDIR/$UPSTREAMDIR.tar.gz $COPYTO
rm -fr "$TEMPDIR"
