#!/bin/sh

ARCH=$(dpkg-architecture -q DEB_TARGET_MULTIARCH)
EJABBERDDIR=$(basename `find /usr/lib -type d -path "*/ejabberd-[0-9][0-9].[0-9][0-9]"`)

mod_dir="debian/$1/usr/lib/$ARCH/$EJABBERDDIR/ebin/"
if [ ! -d  $mod_dir ]; then
	echo "$1: Package does not install any modules."
	exit 0
fi

mods=$(cd "debian/$1/usr/lib/$ARCH/$EJABBERDDIR/ebin/"; ls *.beam | sed 's/.beam$//')

echo '
# Automatically added by dh_moduleupdate
ejabberdctl="/usr/sbin/ejabberdctl"
mods="'$mods'"

if [ "$1" = "configure" ]; then
	# check if ejabberd is running
	$ejabberdctl status > /dev/null || exit 0

	# source /etc/default/ejabberd
	[ -f "/etc/default/ejabberd" ] && . /etc/default/ejabberd

	for mod in $mods; do
		if [ "$($ejabberdctl update_list | grep -c $mod)" -eq "1" ]; then
			echo -n "Upgrading ejabberd module $mod... "
			$ejabberdctl update $mod > /dev/null || { echo "failed"; continue; }
			echo "ok"
		else
			echo "$mod is not enabled or has no update."
		fi
	done
fi
# End automatically added section
' >> debian/$1.postinst.debhelper
