#!/bin/bash

# Copyright 2020-2021 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

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

VERSION=10

APP_ID="ucsschool-kelvin-rest-api"
ADMIN_GROUP="$APP_ID-admins"
UDM_REST_GROUP="UDM-API-enabled-machines"
CN_ADMIN_SECRET_FILE="/var/lib/univention-appcenter/apps/$APP_ID/conf/cn_admin.secret"
TOKEN_SIGN_SECRET_FILE="/var/lib/univention-appcenter/apps/$APP_ID/conf/tokens.secret"
KELVIN_IMPORT_CONFIG_FILE="/var/lib/ucs-school-import/configs/kelvin.json"
KELVIN_IMPORTUSER_HOOKS_PATH="/var/lib/ucs-school-import/kelvin-hooks"
KELVIN_IMPORTUSER_HOOKS_README="${KELVIN_IMPORTUSER_HOOKS_PATH}/README.txt"
UDM_CLIENT_UPDATE_SCRIPT="/var/lib/univention-appcenter/apps/$APP_ID/data/update_openapi_client"

. /usr/share/univention-join/joinscripthelper.lib || exit 1
. /usr/share/univention-appcenter/joinscripthelper.sh || exit 1


main () {
    docker exec $appcenter_apps_ucsschool_kelvin_rest_api_container /usr/bin/univention-config-registry set \
    logrotate/opa/compress="$(ucr get logrotate/opa/compress)" \
    logrotate/opa/create="$(ucr get logrotate/opa/create)" \
    logrotate/opa/missingok="$(ucr get logrotate/opa/missingok)" \
    logrotate/opa/notifempty="$(ucr get logrotate/opa/notifempty)" \
    logrotate/opa/rotate/count="30" \
    logrotate/opa/rotate="daily" \
    ldap/server/name="$(ucr get ldap/server/name)" \
    ldap/server/port="$(ucr get ldap/server/port)" \
    dhcpd/ldap/base="$(ucr get dhcpd/ldap/base)" \
    ucsschool/import/set/netlogon/script/path="$(ucr get ucsschool/import/set/netlogon/script/path)" \
    ucsschool/import/set/homedrive="$(ucr get ucsschool/import/set/homedrive)" \
    ucsschool/import/set/sambahome="$(ucr get ucsschool/import/set/sambahome)" \
    ucsschool/singlemaster="$(ucr get ucsschool/singlemaster)" \
    ucsschool/import/set/serverprofile/path="$(ucr get ucsschool/import/set/serverprofile/path)" \
    ucsschool/validation/logging/backupcount="$(ucr get ucsschool/validation/logging/backupcount)" \
    ucsschool/validation/logging/enabled="$(ucr get ucsschool/validation/logging/enabled)" \
    ucsschool/validation/username/windows-check="$(ucr get ucsschool/validation/username/windows-check)" \
    ucsschool/import/generate/share/marktplatz="$(ucr get ucsschool/import/generate/share/marktplatz)" \
    ucsschool/import/generate/policy/dhcp/searchbase="$(ucr get ucsschool/import/generate/policy/dhcp/searchbase)" \
    ucsschool/import/generate/policy/dhcp/dns/set_per_ou="$(ucr get ucsschool/import/generate/policy/dhcp/dns/set_per_ou)" \
    ucsschool/import/generate/import/group="$(ucr get ucsschool/import/generate/import/group)" \
    ucsschool/ldap/default/container/exam="$(ucr get ucsschool/ldap/default/container/exam)" \
    groups/default/domainusers="$(ucr get groups/default/domainusers)" \
    ucsschool/ldap/default/dcs="$(ucr get ucsschool/ldap/default/dcs)" \
    ucsschool/import/generate/policy/dhcp/dns/clearou="$(ucr get ucsschool/import/generate/policy/dhcp/dns/clearou)"

    if ! [ -e "$TOKEN_SIGN_SECRET_FILE" ]; then
        echo "Storing token key in $TOKEN_SIGN_SECRET_FILE."
        touch "$TOKEN_SIGN_SECRET_FILE"
        chown root:root "$TOKEN_SIGN_SECRET_FILE"
        chmod 640 "$TOKEN_SIGN_SECRET_FILE"
        # prevent "unable to write 'random state'" because $HOME is not set
        export RANDFILE=/.rnd
        openssl rand -hex 32 > "$TOKEN_SIGN_SECRET_FILE" || die
    else
        echo "Using existing token key."
    fi

    if ! [ -e "$CN_ADMIN_SECRET_FILE" ]; then
        echo "Storing cn=admin password in $CN_ADMIN_SECRET_FILE."
        touch "$CN_ADMIN_SECRET_FILE"
        chown root:root "$CN_ADMIN_SECRET_FILE"
        chmod 640 "$CN_ADMIN_SECRET_FILE"
        cat /etc/ldap.secret > "$CN_ADMIN_SECRET_FILE" || die
    else
        echo "Using existing password file."
    fi

    if ! [ -e "$KELVIN_IMPORT_CONFIG_FILE" ]; then
      echo "Creating empty config file for the Import Framework used by Kelvin."
      echo "{}" > "$KELVIN_IMPORT_CONFIG_FILE"
    fi

    if ! [ -e "$KELVIN_IMPORTUSER_HOOKS_README" ]; then
      echo 'Directory for hooks for the UCS@school Kelvin REST API
------------------------------------------------------

The content of this directory is scanned when the Kelvin API
server starts.
If it contains hook classes that inherit from
``ucsschool.importer.utils.import_pyhook.ImportPyHook`` or
``ucsschool.lib.models.hook.Hook``, they are executed
when users are managed through the Kelvin API.
The hooks are very similar to the Python hooks for the UCS@school import. See
UCS@school import manual:
https://docs.software-univention.de/ucsschool-kelvin-rest-api/installation-configuration.html#python-hooks-for-user-object-management-import-hooks

The "__pycache__" directory can be safely ignored.
' > "$KELVIN_IMPORTUSER_HOOKS_README"
    fi

  echo "Creating group for users that are allowed to connect to the Kelvin 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 Kelvin API." \
		--append "users=uid=Administrator,cn=users,$ldap_base" || die

  echo "Creating group '$UDM_REST_GROUP' for machine accounts that are allowed to access the UDM REST API."
  univention-directory-manager groups/group create "$@" --ignore_exists \
    --position "cn=groups,$ldap_base" \
    --set name="$UDM_REST_GROUP" \
    --set description="Machine accounts that are allowed to connect to the UDM REST API." || die

  UDM_REST_GROUP_DN="cn=$UDM_REST_GROUP,cn=groups,$ldap_base"

  echo "Adding Kelvin API machine account '$appcenter_apps_ucsschool_kelvin_rest_api_hostdn' to group '$UDM_REST_GROUP'."
  univention-directory-manager groups/group modify \
    --dn "$UDM_REST_GROUP_DN" \
    --append users="$appcenter_apps_ucsschool_kelvin_rest_api_hostdn" || die

  echo "Whitelisting new group for UDM REST API."
  ucr set directory/manager/rest/authorized-groups/udm-api-enabled-machines="$UDM_REST_GROUP_DN" || die

  echo "Restarting UDM REST API service."
  service univention-directory-manager-rest restart || die
  sleep 1  # prevent [502] Proxy Error, in case of access before UDM REST API is ready

  # Bug #53218: update listener module
  echo "Restarting Univention Directory Listener service."
  service univention-directory-listener restart || die
}

check_openapi_client_knows_ucssschool() {
  OPENAPI_TEST_CODE="import sys; from openapi_client_udm import UsersUserOptions; sys.exit(0 if 'ucsschool_administrator' in UsersUserOptions.openapi_types else 1)"
  if ! univention-app shell "$APP_ID" /usr/bin/python3 -c "$OPENAPI_TEST_CODE"; then
    echo "Building OpenAPI client library in Docker container..."
    univention-app shell "$APP_ID" "$UDM_CLIENT_UPDATE_SCRIPT"
    if univention-app shell "$APP_ID" /usr/bin/python3 -c "$OPENAPI_TEST_CODE"; then
      echo "OK: OpenAPI client library now knows UCS@school types."
    else
      die "FAIL: OpenAPI client library in Docker container still not usable!"
    fi
  else
    echo "OK: OpenAPI client library already knows UCS@school types."
  fi
}


joinscript_init
eval $(ucr shell ldap/base appcenter/apps/ucsschool-kelvin-rest-api/hostdn appcenter/apps/ucsschool-kelvin-rest-api/container)

main "$@"
check_openapi_client_knows_ucssschool

if [ $JS_LAST_EXECUTED_VERSION -lt 9 ] ; then
  mkdir -p /var/lib/univention-appcenter/apps/ucsschool-kelvin-rest-api/data/scripts/
  docker cp $appcenter_apps_ucsschool_kelvin_rest_api_container:/kelvin/fix_nt_acl_on_shares /var/lib/univention-appcenter/apps/ucsschool-kelvin-rest-api/data/scripts/
  /var/lib/univention-appcenter/apps/ucsschool-kelvin-rest-api/data/scripts/fix_nt_acl_on_shares "$@"
	univention-directory-listener-ctrl resync samba-shares
fi

joinscript_save_current_version
exit $?
