#!/bin/bash

# SPDX-FileCopyrightText: 2023 Univention GmbH
#
# SPDX-License-Identifier: AGPL-3.0-only

## joinscript api: bindpwdfile

#
#  Join script that runs on the docker host.
#

# shellcheck disable=SC2034
VERSION=1
APP_ID="id-broker-sddb-builder"
ADMIN_GROUP="$APP_ID-admins"
# shellcheck source=/dev/null
. /usr/share/univention-join/joinscripthelper.lib || exit 1
# shellcheck source=/dev/null
. /usr/share/univention-appcenter/joinscripthelper.sh || exit 1


joinscript_init

KELVIN_MAPPED_CONFIG=/etc/ucsschool/kelvin/mapped_udm_properties.json
KELVIN_SEC_GROUP=ucsschool-kelvin-rest-api-admins
KELVIN_SEC_GROUP_DN="cn=$KELVIN_SEC_GROUP,cn=groups,$(ucr get ldap/base)"
SDDB_MACHINE_ACCOUNT="$(ucr get appcenter/apps/$APP_ID/hostdn)"


test_kelvin_api_app_installed () {
  if  ! univention-app status ucsschool-kelvin-rest-api 1>/dev/null 2>/dev/null ; then
    echo "ERROR: -------------------------------------------------------------------------"
    echo "ERROR: The app 'UCS@school Kelvin Rest API' (ucsschool-kelvin-rest-api) has to"
    echo "ERROR: be installed. Please install the app manually:"
    echo "ERROR: root@$(hostname -s):~# univention-app install ucsschool-kelvin-rest-api"
    echo "ERROR: -------------------------------------------------------------------------"
    return 1
  else
    echo "OK: The app 'UCS@school Kelvin Rest API' (ucsschool-kelvin-rest-api) is installed."
  fi
  return 0
}

setup_access_to_kelvin () {
  if univention-directory-manager groups/group list "$@" --filter "cn=$KELVIN_SEC_GROUP" | grep 'hosts:' | grep -q "$SDDB_MACHINE_ACCOUNT"; then
    echo "SDDB machine account '$SDDB_MACHINE_ACCOUNT' already member of group '$KELVIN_SEC_GROUP'."
  else
    echo "Adding SDDB machine account '$SDDB_MACHINE_ACCOUNT' to group"
    echo "'$KELVIN_SEC_GROUP', so SDDB can access the Kelvin REST API..."
    univention-directory-manager groups/group modify "$@" \
      --dn "$KELVIN_SEC_GROUP_DN" \
      --append hosts="$SDDB_MACHINE_ACCOUNT" || die
  fi
}

add_prop_to_kelvin_mapped_udm_properties () {
  local cls="${1:-}" prop="${2:-}" path="${3:-}"
  python -c "
import json
conf = json.load(open('$path'))
if '$cls' not in conf:
  conf['$cls'] = ['$prop']
else:
  conf_cls = set(conf['$cls'])
  conf_cls.add('$prop')
  conf['$cls'] = sorted(conf_cls)
json.dump(conf, open('$path', 'w'))
"
}

prop_in_kelvin_mapped_udm_properties () {
  local cls="${1:-}" prop="${2:-}" path="${3:-}"
  python -c "
import json, sys
conf = json.load(open('$path'))
sys.exit(int('$prop' not in conf.get('$cls', [])))
"
}

add_prop_to_kelvin_mapped_udm_properties_if_missing () {
  local cls="${1:-}" prop="${2:-}" path="${3:-}"
  if prop_in_kelvin_mapped_udm_properties "$cls" "$prop" "$path";
  then
    echo "Property '$prop' for '$cls' already in Kelvin REST APIs configuration file '$path'."
  else
    echo "Adding '$prop' for '$cls' to Kelvin REST APIs configuration file '$path'..."
    add_prop_to_kelvin_mapped_udm_properties "$cls" "$prop" "$path" || return 1
  fi
}

create_extended_attributes () {
  udm settings/extended_attribute create "$@" \
    --ignore_exists \
    --position "cn=custom attributes,cn=univention,$(ucr get ldap/base)" \
    --set name="entryUUID" \
    --set CLIName="entryUUID" \
    --set ldapMapping="entryUUID" \
    --set shortDescription="entryUUID" \
    --set translationShortDescription='de_DE "entryUUID"' \
    --set longDescription="Internal LDAP database ID" \
    --set translationLongDescription='de_DE "Interne LDAP Datenbank-ID"' \
    --set tabName="LDAP details" \
    --set tabPosition="5" \
    --set translationTabName='de_DE "LDAP Details"' \
    --set groupName="LDAP database details" \
    --set translationGroupName='de_DE "LDAP Datenbankdetails"' \
    --set groupPosition="3" \
    --append module="users/user" \
    --append module="groups/group" \
    --append module="container/ou" \
    --set objectClass="top" \
    --set syntax="string" \
    --set fullWidth="1"

  udm settings/extended_attribute create "$@" \
   --position "cn=custom attributes,cn=univention,$(ucr get ldap/base)" \
   --set name="modifyTimestamp" \
   --set CLIName="modifyTimestamp" \
   --set ldapMapping="modifyTimestamp" \
   --set shortDescription="timestamp of last object modification" \
   --set translationShortDescription='de_DE "Zeitstempel der letzten Objektänderung"' \
   --set longDescription="Database timestamp of the last LDAP object modification, typically UTC" \
   --set translationLongDescription='de_DE "Zeitpunkt der letzten Änderung des LDAP Objekts, typischer Weise UTC"' \
   --set tabName="LDAP details" \
   --set tabPosition="3" \
   --set translationTabName='de_DE "LDAP Details"' \
   --set groupName="object modification" \
   --set translationGroupName='de_DE "Objektveränderung"' \
   --set groupPosition="2" \
   --append  module="users/user" \
   --append module="groups/group" \
   --append module="container/ou" \
   --set objectClass="top" \
   --set syntax="string"
}

restart_kelvin () {
  echo "Restarting UCS@school Kelvin REST API app..."
  univention-app shell ucsschool-kelvin-rest-api /etc/init.d/ucsschool-kelvin-rest-api restart
}

create_extended_attributes "$@"
systemctl restart univention-directory-manager-rest.service

test_kelvin_api_app_installed
setup_access_to_kelvin "$@"
for cls in "school" "school_class" "user" "workgroup"; do
  add_prop_to_kelvin_mapped_udm_properties_if_missing "$cls" "entryUUID" "$KELVIN_MAPPED_CONFIG" || die
  add_prop_to_kelvin_mapped_udm_properties_if_missing "$cls" "modifyTimestamp" "$KELVIN_MAPPED_CONFIG" || die
  for index in $(seq -w 30); do
    add_prop_to_kelvin_mapped_udm_properties_if_missing "$cls" "idBrokerPseudonym00${index}" "$KELVIN_MAPPED_CONFIG" || die
  done
done
for cls in "school_class" "workgroup"; do
  add_prop_to_kelvin_mapped_udm_properties_if_missing "$cls" "ucsschoolSourceUID" "$KELVIN_MAPPED_CONFIG" || die
done
restart_kelvin
ucr set directory/manager/rest/ldap-connection/machine-read/uri="ldap://localhost:7389/"
systemctl restart univention-directory-manager-rest

ldap_base=$(ucr get ldap/base)
echo "Creating group for users that are allowed to connect to the Self-disclosure Database Builder API"
echo "($ADMIN_GROUP)..."
univention-directory-manager groups/group create "$@" --ignore_exists \
  --position "cn=groups,$ldap_base" \
  --set name="$ADMIN_GROUP" \
  --set description="Users that are allowed to connect to the Self-disclosure Database Builder API."
univention-directory-manager groups/group modify "$@" \
  --dn "cn=$ADMIN_GROUP,cn=groups,$ldap_base" \
  --append "users=uid=Administrator,cn=users,$ldap_base" || die


joinscript_save_current_version

exit $?
