#!/bin/sh
set -e

if ! egrep -qv "^(#| *)$" debian/sourceless; then
	echo "No sourceless files specified. Skipping the dfsg tarball creation."
	exit 0
fi

while [ $1 ]; do
	case $1 in
		--upstream-version)
			shift
			VERSION=$1
			;;
		*)
			FILE=$1
	esac
	shift
done

if ! [ ${FILE} ]; then
   echo "Usage: $0 [--upstream-version <version>] <filename>"
   exit 0
fi

UPSTREAM_FILE=$(basename $(readlink -f ${FILE}))
NAME=$(dpkg-parsechangelog -S Source)
if [ $VERSION ]; then
	DFSG_FILE=${NAME}_${VERSION}
else
	DFSG_FILE=${FILE%%.orig*}
	VERSION=${DFSG_FILE##*_}
fi

DFSG_NUM=$(dpkg-parsechangelog -S Version --from ${VERSION} | sed -n 's/.*dfsg\([[:digit:]]*\).*/\1/p')
DFSG_FILE=${DFSG_FILE}+dfsg${DFSG_NUM}.orig.tar

EXT=${UPSTREAM_FILE##*.}
case ${EXT} in
	"gz")
		PACK="gzip -vf"
		UNPACK="gunzip -vf"
		;;
	"bz2")
		PACK="bzip2 -vf"
		UNPACK="bunzip2 -vf"
		;;
	"lzma")
		PACK="lzma -vf"
		UNPACK="unzlma -vf"
		;;
	"xz")
		PACK="xz -vf"
		UNPACK="unxz -vf"
		;;
	*)
		echo "Compression type not supported. Nothing to do..."
		exit 0
esac

cp -i ../${UPSTREAM_FILE} ../${DFSG_FILE}.${EXT}

echo "Unpacking tarball... "
${UNPACK} ../${DFSG_FILE}.${EXT}

OLDIFS=$IFS
IFS='
' # don't remove this
SOURCELESS=$(grep -v ^# debian/sourceless)
for ITEM in $SOURCELESS; do
	echo -n "Deleting '${ITEM}' from tarball... "
	if ! tar --delete --wildcards -f ../${DFSG_FILE} "${ITEM}"; then
		echo "WARNING! THE CONTENT OF THE DEBIAN/SOURCELESS MAY BE WRONG!"
	else
		echo "done"
	fi
done
IFS=$OLDIFS

echo "Packing tarball... "
${PACK} ../${DFSG_FILE}
