#!/bin/sh
#
# Univention horde webclient
#  join script
#
# Copyright 2011-2016 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

set -e

VERSION=1

. /usr/share/univention-lib/all.sh
. /usr/share/univention-join/joinscripthelper.lib

eval "$(univention-config-registry shell)"

joinscript_init

# apache config
apache_cfg="/etc/apache2/ucs-sites.conf.d/horde-app.conf"
container_port="$(ucr get appcenter/apps/horde/ports/80)"
locations="Microsoft-Server-ActiveSync
autodiscover/autodiscover.xml
Autodiscover/Autodiscover.xml
AutoDiscover/AutoDiscover.xml"
if [ ! -e "$apache_cfg" ]; then
        for i in $locations; do
                echo >>"$apache_cfg"
                echo ProxyPass /$i http://127.0.0.1:$container_port/$i timeout=4000 connectiontimeout=600 acquire=3000 retry=6 >>"$apache_cfg"
                echo ProxyPassReverse  /$i http://127.0.0.1:$container_port/$i >>"$apache_cfg"
        done
        invoke-rc.d apache2 reload
fi

# use the first IMAP server as smtp and imap server
mailserver="$(univention-ldapsearch -LLL univentionService=IMAP cn | grep "^cn: " | sed s/"^cn: "// | head -n1)"
if [ -n "$mailserver" ]; then
        mailserver="$mailserver.$domainname"
        univention-app configure horde --set horde/mailer/params/host="$mailserver" horde/imap/hostspec="$mailserver"
fi

# configure webmaster
maildomain="$(univention-ldapsearch -LLL objectClass=univentionMailDomainname cn | grep "^cn: " | sed s/"^cn: "// | head -n1)"
if [ -n "$maildomain" ]; then
        univention-app configure horde --set horde/problems/mail="webmaster@$maildomain"
fi

# initial horde configuration
univention-app shell horde /usr/share/univention-mail-horde/univention-mail-horde-configuration "Administrator"

# add service to my host object
ucs_addServiceToLocalhost Horde "$@"

joinscript_save_current_version

exit 0