#!/bin/sh
#
# Generates debian/control from debian/control.in by appending a uuencoded
# string representing a png icon named after a package defined in
# debian/control.in and located under debian/package-icons.
#
# For example, if debian/control.in defines a package called "foo" and a png
# named "foo.png" is found under debian/package-icons, then "foo.png" is assumed
# to be of the prescribed size of 26x26 pixels, and will be added as a
# "XB-Maemo-Icon-26: <uuencoded icon file contents>" tag to the generated
# "debian/control" file.

echo_icon() # $1 = package_name
	{
	echo -n 'XB-Maemo-Icon-26: '
	uuencode -m debian/package-icons/$1.png - | grep -vE '^(begin-base64|====$)' | awk '{printf $1;}'
	echo ''
	}

CURRENT_PACKAGE=""

cat debian/control | \
while true; do
	if read; then
		DO_ECHO=1
		if echo $REPLY | grep -q '^Package: '; then
			CURRENT_PACKAGE=`echo $REPLY | awk '{print $2;}'`
		fi
		if echo $REPLY | grep -q '^XB-Maemo-Icon-26: '; then
			DO_ECHO=0
		fi
		if test "$REPLY" = ""; then
			if test -f debian/package-icons/$CURRENT_PACKAGE.png; then
				echo_icon $CURRENT_PACKAGE
			elif test "" != "$CURRENT_PACKAGE"; then
				echo -e "\033[7m$CURRENT_PACKAGE: No icon 'debian/package-icons/$CURRENT_PACKAGE.png'\033[0m" > /dev/fd/2
			fi
			CURRENT_PACKAGE=""
		fi
		if test $DO_ECHO -eq 1; then
			echo $REPLY
		fi
	else
		if test -f debian/package-icons/$CURRENT_PACKAGE.png; then
			echo_icon $CURRENT_PACKAGE
		elif test "" != "$CURRENT_PACKAGE"; then
			echo -e "\033[7m$CURRENT_PACKAGE: No icon 'debian/package-icons/$CURRENT_PACKAGE.png'\033[0m" > /dev/fd/2
		fi
		break
	fi
done > debian/control.icons && mv -f debian/control.icons debian/control
