#!/bin/sh
#
# Set up jwchat to work out of the box.

set -e

# Set hostname for ejabberd and jwchat
echo "ejabberd ejabberd/hostname string `cat /etc/hostname`" | debconf-set-selections
echo "jwchat jwchat/ApacheServerName string `cat /etc/hostname`" | debconf-set-selections

# An alternative XMPP server is prosody
apt-get install -y jwchat ejabberd

# Enable IPv6 for c2s, s3s, and http connections.
if ! grep -q inet6 /etc/ejabberd/ejabberd.cfg ; then
    sed -i '/{5222, ejabberd_c2s, \[/a \
			inet6,' /etc/ejabberd/ejabberd.cfg
    sed -i '/{5269, ejabberd_s2s_in, \[/a \
                           inet6,' /etc/ejabberd/ejabberd.cfg
    sed -i '/{5280, ejabberd_http, \[/a \
                         inet6,' /etc/ejabberd/ejabberd.cfg
fi

# Enable BOSH module for ejabberd
if ! grep -q mod_http_bind /etc/ejabberd/ejabberd.cfg ; then
    sed -i '/mod_last/i \
  {mod_http_bind, []},' /etc/ejabberd/ejabberd.cfg
fi

# setup jwchat apache conf
cat > /etc/apache2/conf-available/jwchat.conf <<'EOF'
Alias /jwchat /usr/share/jwchat/www

<Directory /usr/share/jwchat/www>
    Options +Indexes +Multiviews +FollowSymLinks
</Directory>

# proxy for BOSH server
ProxyPass /http-bind/ http://localhost:5280/http-bind/
ProxyPassReverse /http-bind/ http://localhost:5280/http-bind/
<Proxy *>
    Allow from all
</Proxy>
EOF

a2dissite jwchat
a2enconf jwchat

# Remove SSL keys from images, will be generated on first boot.
rm -f /etc/ejabberd/ejabberd.pem
