#!/bin/sh
# Repack an upstream tarball, unpacking waf files inside it.
#
# Meant to be run by uscan(1) as the "command param", after repacking
# (if any) by mk-origtargz. So you shouldn't give "repacksuffix" to
# debian/watch; instead you should set it below; however this should
# still match the dversionmangle in that file.

repacksuffix="+dfsg"
unwaf_paths="ns-* pybindgen-*"

# You shouldn't need to change anything below here.
# But I did to rename the directory in the tar: mv mv ns-allinone-${upstream} "${source}-${upstream}" [Mt]
# And to remove the pyc files before moving them out of the hidden directory

USAGE="Usage: $0 --upstream-version version filename"

test "$1" = "--upstream-version" || { echo >&2 "$USAGE"; exit 2; }
upstream="$2"
filename="$3"

source="$(dpkg-parsechangelog -SSource)"
newups="${upstream}${repacksuffix}"
basedir="$(dirname "$filename")"

# Binary parts in waf files are not allowed in debian source packages
unpack_waf() {
	local olddir="$PWD"
	cd "$1"
	test -x ./waf || return 1
	echo "Cleaning $1/waf. Extracted content:"
	./waf --help > /dev/null
	rm -rvf .waf-*
	sed -i '/^#==>$/,$d' waf
	
	rm -fv `find -name '*.pyc'` utils.pyc wutils.pyc # generated when executing waf
	cd "$olddir"
}

set -e

rm -rf temp ; mkdir temp
cd temp
tar -xf "../$filename"

mv ns-allinone-* "${source}-${upstream}"
cd "${source}-${upstream}"

for i in $unwaf_paths; do unpack_waf "$i"; done
cd ..
mv "${source}-${upstream}" "${source}-${newups}"
tar -cf "../$basedir/${source}_${newups}.orig.tar" "${source}-${newups}"
gzip -9f "../$basedir/${source}_${newups}.orig.tar"
rm -rf "${source}-${newups}"

cd ../ # out of temp
rm -rf temp

echo "Package-specific repacking done"
