#!/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=6

. /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" "$@"

# 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"

# customize proxy settings
echo "Activate Apache2 module proxy_wstunnel for EGroupware websocket reverse proxy configuration"
a2enmod proxy_wstunnel

# 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

# required for push / websocket
RewriteEngine on
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteCond %{HTTP:Connection} upgrade [NC]
RewriteRule /egroupware/push ws://127.0.0.1:$port/egroupware/push [P]

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

RewriteRule ^/.well-known/(caldav|carddav|openid-configuration)$ http://127.0.0.1:$port$0 [P]
RedirectMatch ^(/principals/users/.*)$ /egroupware/groupdav.php\$1
RedirectMatch ^/egroupware$ /egroupware/index.php

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

sleep 30

install_log="/var/lib/egroupware/egroupware-docker-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')"
    udm_rest_insecure=false
    appliance_id="$(ucr get umc/web/appliance/id)"
    if [ "$appliance_id" = "egroupware" ]; then
        # On appliance mode, the server works with a preliminary, unknown cert
        echo "Appliance mode has been detected for $appliance_id."
        udm_rest_insecure=true
    fi
    date >> "$install_log"
    univention-app shell egroupware bash -c "UDM_REST_INSECURE=$udm_rest_insecure \
        /usr/share/egroupware/doc/rpm-build/post_install.php \
        --admin_user 'Administrator' \
        --admin_passwd '*unchanged*' \
        --db_host 'db' \
        --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"
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