#!/bin/bash
#
# App join script
#
# Copyright 2022 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/>.

## joinscript api: bindpwdfile

VERSION="3"

. /usr/share/univention-appcenter/joinscripthelper.sh

joinscript_init

ldap_base="$(ucr get ldap/base)"
dcd_redis_replication_mode="$(ucr get dcd/redis/replication/mode)"

ucs_addServiceToLocalhost "$SERVICE" "$@"

docker cp $(ucr get appcenter/apps/dcd/container):/resources/dcd.acl /var/lib/univention-appcenter/apps/dcd/conf/67dcd.acl || die

ucs_registerLDAPExtension "$@" \
    --ucsversionstart "4.4-0" --ucsversionend "5.99-0" \
    --packagename dcd \
    --packageversion "$APP_VERSION" \
    --acl "/var/lib/univention-appcenter/apps/dcd/conf/67dcd.acl" || die

univention-directory-manager groups/group create "$@" --ignore_exists \
    --position "cn=groups,$ldap_base" \
    --set name="dcd_readonly" \
    --set description="Read keys in Distributed Configuration Database" || die

univention-directory-manager groups/group create "$@" --ignore_exists \
    --position "cn=groups,$ldap_base" \
    --set name="dcd_write" \
    --set description="Modify keys in Distributed Configuration Databaes" || die

univention-directory-manager groups/group create "$@" --ignore_exists \
    --position "cn=groups,$ldap_base" \
    --set name="dcd_admin" \
    --set description="Create and delete keys in the Distributed Configuration Database" || die

if [[ "$dcd_redis_replication_mode" == "master" ]]; then
data="$(python3 <<-%EOF
import os
import json
import bz2
import base64
from univention.config_registry import ConfigRegistry

ucr = ConfigRegistry().load()

fqdn = '%s.%s' % (ucr.get('hostname'), ucr.get('domainname'))


conf_path='/var/lib/univention-appcenter/apps/dcd/conf/'
dcdreplicapwd = ''
with open('/var/lib/univention-appcenter/apps/dcd/conf/dcdreplica.secret', 'r') as fd:
    dcdreplicapwd = fd.read().strip()
dcdapiuserpwd = ''
with open('/var/lib/univention-appcenter/apps/dcd/conf/dcdapiuser.secret', 'r') as fd:
    dcdapiuserpwd = fd.read().strip()
with open('/var/lib/univention-appcenter/apps/dcd/conf/dcdrediscert/cert.pem', 'r') as fd:
    cert = fd.read().strip()
with open('/var/lib/univention-appcenter/apps/dcd/conf/dcdrediscert/private.key', 'r') as fd:
    private = fd.read().strip()
with open('/var/lib/univention-appcenter/apps/dcd/conf/dcdrediscert/ca.crt', 'r') as fd:
    ca = fd.read().strip()
data = json.dumps({'passwords': {'dcdreplica': dcdreplicapwd, 'dcdapiuser': dcdapiuserpwd}, 'installations': [fqdn], 'certificates': {'cert.pem': cert, 'private.key': private, 'ca.crt': ca}})
print(base64.b64encode(bz2.compress(data.encode('UTF-8'))).decode('UTF-8'))
%EOF
)" || die
    univention-directory-manager settings/data create "$@" --ignore_exists \
        --position="cn=data,cn=univention,$ldap_base" \
        --set name="dcdconfig" \
        --set data_type="application/json" \
        --set data="$data" || die
else
data="$(python3 <<-%EOF
import bz2
import base64
import json
from univention.udm import UDM
from univention.config_registry import ConfigRegistry

ucr = ConfigRegistry().load()

udm = UDM.machine().version(2)
obj = udm.get("settings/data").get_by_id("dcdconfig")
data = obj.props.data.raw
data = json.loads(data.decode("utf-8"))

installations = data["installations"]

fqdn = '%s.%s' % (ucr.get('hostname'), ucr.get('domainname'))

if fqdn not in installations:
    installations.append(fqdn)

data = json.dumps(data)
print(base64.b64encode(bz2.compress(data.encode('UTF-8'))).decode('UTF-8'))
%EOF
)" || die
    univention-directory-manager settings/data modify "$@" \
        --dn "cn=dcdconfig,cn=data,cn=univention,$ldap_base" \
        --set data="$data" || die
fi

docker cp $(ucr get appcenter/apps/dcd/container):/resources/dcd-replication.py /usr/lib/univention-directory-listener/system/dcd-replication.py || die
service univention-directory-listener restart


cat << EOF >"/etc/apache2/ucs-sites.conf.d/1dcdwebsockets.conf"
         RewriteCond %{HTTP:Upgrade}= websocket [NC]
         RewriteRule /univention/dcd/(.*) ws://127.0.0.1:$(ucr get appcenter/apps/dcd/ports/8000)/univention/dcd/\$1 [P,L]
EOF
a2enmod proxy_wstunnel
systemctl restart apache2


joinscript_save_current_version

exit 0
