#!/bin/bash
#
# Copyright 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/>.

VERSION=3

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

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

set -e

joinscript_init

# add service
SERVICE="EGroupware"
ucs_addServiceToLocalhost "$SERVICE" "$@"

# enable ssl in container
univention-app shell egroupware a2enmod ssl
univention-app shell egroupware a2ensite default-ssl
univention-app shell egroupware service apache2 restart

# setup link
ucr set \
ucs/web/overview/entries/admin/egroupware-adm/description/de="Weitergehende Konfigurationen (admin, /etc/egroupware-admin.secret)" \
ucs/web/overview/entries/admin/egroupware-adm/description="Further configuration (admin, /etc/egroupware-admin.secret)" \
ucs/web/overview/entries/admin/egroupware-adm/icon="$ucs_web_overview_entries_service_egroupware_icon" \
ucs/web/overview/entries/admin/egroupware-adm/label/de="EGroupware Setup" \
ucs/web/overview/entries/admin/egroupware-adm/label="EGroupware Setup" \
ucs/web/overview/entries/admin/egroupware-adm/link="/egroupware/setup"


# active sync apache config
port="$appcenter_apps_egroupware_ports_80"
eg_options="timeout=4000 connectiontimeout=600 acquire=3000 retry=6"
as_options="timeout=4000 connectiontimeout=600 acquire=3000 retry=6"
cat <<-EOF >"/etc/apache2/ucs-sites.conf.d/egroupware-app.conf"
# generated by egroupware join script, do not edit manually
RequestHeader set X-Forwarded-Proto "https" env=HTTPS
ProxyPass /egroupware/ http://127.0.0.1:$port/egroupware/ $eg_options
ProxyPassReverse /egroupware/ http://127.0.0.1:$port/egroupware/

ProxyPass /Microsoft-Server-ActiveSync http://127.0.0.1:$port/Microsoft-Server-ActiveSync $as_options
ProxyPassReverse /Microsoft-Server-ActiveSync http://127.0.0.1:$port/Microsoft-Server-ActiveSync

RedirectMatch ^/.well-known/(caldav|carddav)$ /egroupware/groupdav.php/
RedirectMatch ^(/principals/users/.*)$ /egroupware/groupdav.php\$1
EOF
invoke-rc.d apache2 reload

# create egroupware system user
if [ ! -e /etc/egroupware.secret ]; then
    password="$(makepasswd)"
    pwdfile="/etc/egroupware.secret"
    touch "$pwdfile"
    chmod 600 "$pwdfile"
    echo -n "$password" > "$pwdfile"
else
    password="$(cat /etc/egroupware.secret)"
fi
username="egroupware-$hostname"
groups_default_domainadmins=$(custom_groupname "Domain Admins")
udm container/cn create "$@" --ignore_exists \
    --set name="egroupware"
udm users/user create "$@" --ignore_exists \
    --position "cn=egroupware,$ldap_base" \
    --set username="$username" \
    --set password="$password" \
    --set firstname="$SERVICE Service" \
    --set lastname="LDAP Account" \
    --set description="Account used by $SERVICE to authenticate against LDAP directory" \
    --set objectFlag="hidden" \
    --set primaryGroup="cn=$groups_default_domainadmins,cn=groups,$ldap_base" \
    --option ldap_pwd || die
udm users/user modify "$@" \
    --dn "uid=$username,cn=egroupware,$ldap_base" \
    --set password="$password" || true
udm groups/group modify "$@" \
    --dn "cn=$groups_default_domainadmins,cn=groups,$ldap_base" \
    --append users="uid=$username,cn=egroupware,$ldap_base" || true

install_log="/root/egroupware-epl-install.log"

# only installation
if [ $JS_LAST_EXECUTED_VERSION = 0 ]; then

    # init egroupware
    db_host="$(univention-app shell egroupware printenv DB_HOST | tr -d '\r')"
    date >> "$install_log"
    univention-app shell egroupware \
        /usr/share/egroupware/doc/rpm-build/post_install.php \
        --distro univention \
        --admin_user "Administrator" \
        --admin_passwd "*unchanged*" \
        --db_host "$db_host" \
        --db_pass "$(< /etc/mysql-egroupware.secret)" \
        --db_name egroupware \
        --db_user egroupware \
        --ldap_admin "uid=$username,cn=egroupware,$ldap_base" \
        --ldap_admin_pw "$password" \
        --ldap_root_dn "uid=$username,cn=egroupware,$ldap_base" \
        --ldap_root_pw "$password" 2>&1 > "$install_log"
    cat "$install_log"
else
    univention-app shell egroupware /usr/share/egroupware/doc/rpm-build/post_install.php
fi

 # save setup password
if [ ! -e /etc/egroupware-admin.secret ]; then
    shopt -s extglob
    mapfile -t setup_file < "$install_log"
    for ((index=0; index <= ${#setup_file[@]}; index++)); do
        if [[ "${setup_file[index]}" =~ .*Setup\ username:.* ]]; then
            echo "${setup_file[index+1]##*( )password:*( )}" > /etc/egroupware-admin.secret
            chmod 640 /etc/egroupware-admin.secret
            break
        fi 
    done
    shopt -u extglob
fi

univention-app shell egroupware chown -R www-data:www-data /var/lib/egroupware/

joinscript_save_current_version

exit 0