#!/bin/sh

if [ ! -e debian/compat ] ; then
	echo "Couldn't find debian/compat"
	echo "Please execute the script from within the unpacked src package"
	exit 1
fi

if ! which quilt > /dev/null ; then
	echo "Please install quilt"
	exit 1
fi

if grep -sq "3.0 (quilt)" debian/source/format || [ -e .pc ] ; then
	# great, we have the new source format or we already use quilt
	# so just add another patch
	export QUILT_PATCHES=debian/patches
	quilt new glib-single-include.patch
else
	mkdir .quilt-patches
	export QUILT_PATCHES=.quilt-patches
	quilt new glib-single-include.patch
fi
files=$(mktemp)
grep -lsRE "#include\s*<(glib/.*|glibconfig.h)>" * > $files

while read file ; do
	quilt add "$file"

	includes=$(sed -n "s/#include <glib\/\(.*\)>.*/\1/p" "$file" | \
		   sed -e "/gi18n.h/d"  -e "/gi18n-lib.h/d" \
		       -e "/gstdio.h/d" -e "/gprintf.h/d")

	for i in $includes ; do
		sed -i "s/#include\s*<glib\/$i>/#include <glib.h>/" "$file"
	done
	sed -i "s/#include\s*<glibconfig.h>/#include <glib.h>/" "$file"
	# Get line of first match and skip that
	line=$(grep -n -m 1 "#include <glib.h>" $file|cut -f1 -d':')
	line=$(($line+1))
	
	sed -i -e "$line,$ s/#include\s*<glib.h>/DELETE_GLIB_H_INCLUDE/" \
	       -e "/DELETE_GLIB_H_INCLUDE/ d" "$file"
done < $files

quilt refresh

# Cleanup
if [ -d .quilt-patches ] ; then
	quilt pop
	mv .quilt-patches/glib-single-include.patch .
	rm -rf .quilt-patches
	rm -rf .pc
	echo "Created patch $(pwd)/glib-single-include.patch"
	echo "Please add it to your package so it is correctly applied"
else
	echo "Created patch debian/patches/glib-single-include.patch"
	echo "and added it to debian/patches/series"
fi

rm $files;
