#!/bin/sh -e

CONFIG_FILE=/etc/ejabberd/ejabberd.cfg

show_usage()
{
	echo 'Usage:'
	echo "    $0 --policy"
	echo "    $0 --port=<port> --host=<hostname> --password=<password> [--config=<config-file>]"
	exit 1
}

port=
host=
password=

TEMP=`getopt -n "$0" -o h -l policy,port:,host:,password:,config: -- "$@"` || show_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
	--policy)
		echo 'multi'
		exit 0
		;;
	--port) shift; port=$1
		;;
	--host) shift; host=$1
		;;
	--password) shift; password=$1
		;;
	--config) shift; CONFIG_FILE=$1
		;;
	--) shift; break
		;;
	esac
	shift
done

[ -n "$port" ] || show_usage
[ -n "$host" ] || show_usage
[ -n "$password" ] || show_usage

exit_handler()
{
	local rc=$?
	trap - EXIT
	if [ -d "$JC_TEMPDIR" ]; then
		rm -f "$JC_TEMPDIR/header" "$JC_TEMPDIR/footer" "$JC_TEMPDIR/body" "$JC_TEMPDIR/ejabberd.cfg"
		rmdir "$JC_TEMPDIR"
	fi
	exit $rc
}
trap exit_handler HUP PIPE INT QUIT TERM EXIT

# Check if config has automation sections
egrep -q '^% <jabber-config>' $CONFIG_FILE || {
	echo "ejabberd: unable to find opening automation tag <jabber-config> - config file editing failed"
	exit 1
}
egrep -q '^% </jabber-config>' $CONFIG_FILE || {
	echo "ejabberd: unable to find closing automation tag </jabber-config> - config file editing failed"
	exit 1
}

# Split config into parts
JC_TEMPDIR=`mktemp -td`
sed '/^% <jabber-config>/q' <$CONFIG_FILE >"$JC_TEMPDIR/header"
sed -n '/^% <jabber-config>/,/^% <\/jabber-config>/p' <$CONFIG_FILE | sed '1d; $d' >"$JC_TEMPDIR/body"
sed -n '/^% <\/jabber-config>/,$p' <$CONFIG_FILE >"$JC_TEMPDIR/footer"

# Check if it's there but disabled
LINE="{$port, ejabberd_service, [{ip, {127, 0, 0, 1}}, {access, all}, {host, \"$host\", [{password, \"$password\"}]}]},"
if egrep -q "% *{$port, ejabberd_service, " "$JC_TEMPDIR/body"; then
	echo "ejabberd: service \"$host\" is disabled"
elif grep -q "{$port, ejabberd_service, " "$JC_TEMPDIR/body"; then
	echo "ejabberd: reinstalling service \"$host\""
	sed -i "s!{$port, ejabberd_service, .*!$LINE!" "$JC_TEMPDIR/body"
else
	echo "ejabberd: adding new service \"$host\""
	echo "$LINE" >>"$JC_TEMPDIR/body"
fi

# Recollect parts to create a new config file
cat "$JC_TEMPDIR/header" "$JC_TEMPDIR/body" "$JC_TEMPDIR/footer" >"$JC_TEMPDIR/ejabberd.cfg"

# Replace old config if it differs
if ! diff -q "$CONFIG_FILE" "$JC_TEMPDIR/ejabberd.cfg" >/dev/null; then
	echo "ejabberd: updating config file"
	mv -f "$CONFIG_FILE" "${CONFIG_FILE}.old"
	mv -f "$JC_TEMPDIR/ejabberd.cfg" "$CONFIG_FILE"
fi
