#!/bin/bash

progctl=/usr/sbin/ejabberdctl

SYS_DOMAIN_FILE=/etc/sysconfig/iiab_domain_name
OUR_DOMAIN_FILE=/etc/sysconfig/ejabberd_domain_name

setup_online_srg() {

    if [ -e /var/lib/ejabberd/online_src_created ]; then
	return 0
    fi;

    # give ejabberd a bit of time to startup on XO-1 HW :-)
    sleep 10;

    short_host=`hostname -s`
    domain=`cat "$SYS_DOMAIN_FILE"`

    # Note: grep -q exits as soon as the match is found, which ejabberdctl
    # doesn't like. So we send the output to /dev/null instead - more
    # portable too.
    #
    # ejabberdctl should handle SIGPIPE without messing up, but that's
    # a minor problem anyway.
    #
    if ! ejabberdctl srg_list "$short_host.$domain" | grep '^Online$' > /dev/null ; then
	# ejabberdctl doesn't like spaces in the description field.
	# backslashes work - but escaping is better left alone for now :-)
	ejabberdctl srg_create Online "$short_host.$domain" \
	    Online "Created_by_ejabberd_init" Online
	[ $? -eq 0 ] || return 1
    fi

    if ! ejabberdctl srg_get_info Online "$short_host.$domain" | grep '^online_users: true$' > /dev/null ; then
	ejabberdctl srg_user_add '@online@' "$short_host.$domain" \
	    Online "$short_host.$domain"
	[ $? -eq 0 ] || return 1
    fi

    # mark success
    touch /var/lib/ejabberd/online_src_created
}

setup_online_srg