#!/bin/sh
#
# Univention Self Service Passwordreset UMC
#  join script
#
# SPDX-FileCopyrightText: 2015-2026 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

## joinscript api: bindpwdfile

VERSION=4

. /usr/share/univention-join/joinscripthelper.lib
. /usr/share/univention-lib/umc.sh
. /usr/share/univention-lib/ldap.sh
. /usr/share/univention-lib/base.sh

joinscript_init

eval "$(ucr shell)"

if [ "$server_role" = "domaincontroller_master" -o "$server_role" = "domaincontroller_backup" ]; then
	ucs_addServiceToLocalhost "univention-self-service-passwordreset-umc" "$@" || die

	if ! echo "\du selfservice" | su - postgres -c psql | grep -q "selfservice"; then
		echo "Creating selfservice user"
		su - postgres -c "echo \"CREATE ROLE selfservice WITH LOGIN;\" | psql" || die "Could not create selfservice postgres user."
	fi

	if ! echo '\list' | su - postgres -c psql | grep -q "selfservice"; then
		echo "Creating selfservice database"
		su - postgres -c "createdb selfservice -E UTF8 -O selfservice -T template0" || die "Could not create selfservice postgres database."
	fi

	DB_SECRET_FILE="/etc/self-service-db.secret"
	if [ ! -f $DB_SECRET_FILE ]; then
		echo "Generating new DB password..."
		selfservice_pwd="$(makepasswd --chars 20)"
		touch "$DB_SECRET_FILE"
		chown root:root "$DB_SECRET_FILE"
		chmod 600 "$DB_SECRET_FILE"
		echo "$selfservice_pwd" > "$DB_SECRET_FILE"
	else
		selfservice_pwd="$(cat "$DB_SECRET_FILE")"
	fi
	su - postgres -c "echo \"ALTER ROLE selfservice WITH ENCRYPTED PASSWORD '$selfservice_pwd';\" | psql" || die "Could not set selfservice database password."
fi
ucs_registerLDAPExtension "$@" --schema /usr/share/univention-self-service/self-service-passwordreset.schema

groups_default_administrators=$(custom_groupname "Administrators")
groups_default_domainadmins=$(custom_groupname "Domain Admins")
groups_default_domainusers=$(custom_groupname "Domain Users")

univention-config-registry set \
	umc/self-service/enabled?yes \
	umc/self-service/passwordreset/blacklist/groups?"$groups_default_administrators,$groups_default_domainadmins" \
	umc/self-service/passwordreset/whitelist/groups?"$groups_default_domainusers" \
	umc/self-service/profiledata/blacklist/groups?"$groups_default_administrators,$groups_default_domainadmins" \
	umc/self-service/profiledata/whitelist/groups?"$groups_default_domainusers" \
	umc/self-service/account-deregistration/blacklist/groups?"$groups_default_administrators,$groups_default_domainadmins" \
	umc/self-service/account-deregistration/whitelist/groups?"$groups_default_domainusers" \
	umc/self-service/passwordreset/email/enabled?yes \
	umc/self-service/passwordreset/email/server?localhost \
	umc/self-service/passwordreset/email/sender_address?"Password Reset Service <noreply@$hostname.$domainname>" \
	umc/self-service/passwordreset/external/enabled?no \
	umc/self-service/passwordreset/sms/enabled?no \
	umc/self-service/passwordreset/limit/total/minute?120 \
	umc/self-service/passwordreset/limit/total/hour?200 \
	umc/self-service/passwordreset/limit/total/day?1000 \
	umc/self-service/passwordreset/limit/per_user/minute?10 \
	umc/self-service/passwordreset/limit/per_user/hour?60 \
	umc/self-service/passwordreset/limit/per_user/day?120

udm settings/extended_attribute create "$@" --ignore_exists \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name="UniventionPasswordSelfServiceEmail" \
	--set CLIName="PasswordRecoveryEmail" \
	--set shortDescription="Password recovery e-mail address" \
	--append translationShortDescription='"de_DE" "E-Mail-Adresse zur Passwort-Wiederherstellung"' \
	--append translationShortDescription='"fr_FR" "Adresse e-mail pour la réinitialisation du mot de passe"' \
	--set longDescription="During the password recovery process an e-mail is sent to the specified e-mail address. Password recovery via e-mail is only available for users if configured and enabled by the administrator." \
	--append translationLongDescription='"de_DE" "An diese E-Mail-Adresse wird während der Passwort-Wiederherstellung eine Mail verschickt. Der Mail-Versand steht dem Benutzer nur zur Verfügung, wenn dieser vom Administrator eingerichtet und freigeschaltet wurde."' \
	--append translationLongDescription='"fr_FR" "Lors de la réinitialisation du mot de passe, un e-mail est envoyé à l’adresse spécifiée. La réinitialisation du mot de passe par e-mail est disponible pour les utilisateurs et utilisatrices uniquement si elle a été activée et configurée par l’administrateur ou l’administratrice."' \
	--set tabAdvanced=0 \
	--set tabName="Password recovery" \
	--append translationTabName='"de_DE" "Passwort-Wiederherstellung"' \
	--append translationTabName='"fr_FR" "Réinitialisation du mot de passe"' \
	--set module="users/user" \
	--set syntax=emailAddress \
	--set default="" \
	--set multivalue=0 \
	--set valueRequired=0 \
	--set mayChange=1 \
	--set doNotSearch=0 \
	--set objectClass=univentionPasswordSelfService \
	--set ldapMapping=univentionPasswordSelfServiceEmail \
	--set deleteObjectClass=0 \
	--set overwriteTab=0 \
	--set fullWidth=1 || die

udm settings/extended_attribute create "$@" --ignore_exists \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name="UniventionPasswordSelfServiceMobile" \
	--set CLIName="PasswordRecoveryMobile" \
	--set shortDescription="Mobile phone number" \
	--append translationShortDescription='"de_DE" "Mobilfunknummer"' \
	--append translationShortDescription='"fr_FR" "Numéro de téléphone portable"' \
	--set longDescription="During the password recovery process a SMS is sent to the specified mobile phone number. Password recovery via SMS is only available for users if configured and enabled by the administrator." \
	--append translationLongDescription='"de_DE" "An diese Mobilfunknummer wird während der Passwort-Wiederherstellung eine SMS verschickt. Der SMS-Versand steht dem Benutzer nur zur Verfügung, wenn dieser vom Administrator eingerichtet und freigeschaltet wurde."' \
	--append translationLongDescription='"fr_FR" "Lors de la réinitialisation du mot de passe, un SMS est envoyé au numéro de portable spécifié. La réinitialisation du mot de passe par SMS est disponible pour les utilisateurs et utilisatrices uniquement si elle a été activée et configurée par l’administrateur ou l’administratrice."' \
	--set tabAdvanced=0 \
	--set tabName="Password recovery" \
	--append translationTabName='"de_DE" "Passwort-Wiederherstellung"' \
	--append translationTabName='"fr_FR" "Réinitialisation du mot de passe"' \
	--set module="users/user" \
	--set syntax=phone \
	--set default="" \
	--set multivalue=0 \
	--set valueRequired=0 \
	--set mayChange=1 \
	--set doNotSearch=0 \
	--set objectClass=univentionPasswordSelfService \
	--set ldapMapping=univentionPasswordSelfServiceMobile \
	--set deleteObjectClass=0 \
	--set overwriteTab=0 \
	--set fullWidth=1 || die

udm settings/extended_attribute create "$@" --ignore_exists \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name="UniventionPasswordRecoveryEmailVerified" \
	--set CLIName="PasswordRecoveryEmailVerified" \
	--set shortDescription="Email address verified" \
	--append translationShortDescription='"de_DE" "E-Mail-Adresse verifiziert"' \
	--append translationShortDescription='"fr_FR" "Adresse e-mail vérifiée"' \
	--set longDescription="This attribute indicates whether an email address is verified or not. The value is set to False both by default and in case PasswordRecoveryMail is changed. When an email address is verified the value will be set to True. " \
	--append translationLongDescription='"de_DE" "Dieses Attribut zeigt an, ob eine E-Mail-Adresse bereits verifiziert ist oder nicht. Anfänglich und bei Änderung der PasswordRecoveryMail ist der Wert auf False gesetzt. Wenn es zur Verifikation einer E-Mail-Adresse kommt, wird der Wert auf True gesetzt."' \
	--append translationLongDescription='"fr_FR" "Cet attribut indique si une adresse e-mail a déjà été vérifiée ou non. La valeur est réglée sur False par défaut et lorsque PasswordRecoveryMail est modifié. Lorsque’une adresse e-mail a été vérifiée, la valeur est réglée sur True."' \
	--set tabAdvanced=0 \
	--set tabName="Password recovery" \
	--append translationTabName='"de_DE" "Passwort-Wiederherstellung"' \
	--append translationTabName='"fr_FR" "Réinitialisation du mot de passe"' \
	--set module="users/user" \
	--set syntax="TrueFalseUpper" \
	--set multivalue=0 \
	--set valueRequired=0 \
	--set mayChange=1 \
	--set doNotSearch=0 \
	--set objectClass=univentionPasswordSelfService \
	--set ldapMapping=univentionPasswordRecoveryEmailVerified \
	--set deleteObjectClass=0 \
	--set overwriteTab=0 \
	--set fullWidth=1 || die

udm settings/extended_attribute create "$@" --ignore_exists \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name="UniventionRegisteredThroughSelfService" \
	--set CLIName="RegisteredThroughSelfService" \
	--set shortDescription="Self-registration" \
	--append translationShortDescription='"de_DE" "Selbstregistrierung"' \
	--append translationShortDescription='"fr_FR" "Auto-inscription"' \
	--set longDescription="This attribute indicates whether a user has self-registered through the Self Service module." \
	--append translationLongDescription='"de_DE" "Dieses Attribut zeigt an, ob sich ein User selbst über das Self-Service-Modul registriert hat."' \
	--append translationLongDescription='"fr_FR" "Cet attribut indique si un utilisateur ou une utilisatrice a utilisé le module de libre-service pour s’inscrire par ses propres moyens."' \
	--set tabAdvanced=0 \
	--set tabName="Password recovery" \
	--append translationTabName='"de_DE" "Passwort-Wiederherstellung"' \
	--append translationTabName='"fr_FR" "Réinitialisation du mot de passe"' \
	--set module="users/user" \
	--set syntax="TrueFalseUpper" \
	--set multivalue=0 \
	--set valueRequired=0 \
	--set mayChange=1 \
	--set doNotSearch=0 \
	--set objectClass=univentionPasswordSelfService \
	--set ldapMapping=univentionRegisteredThroughSelfService \
	--set deleteObjectClass=0 \
	--set overwriteTab=0 \
	--set fullWidth=1 || die

udm settings/extended_attribute create "$@" --ignore_exists \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name="UniventionDeregisteredThroughSelfService" \
	--set CLIName="DeregisteredThroughSelfService" \
	--set shortDescription="Self-deregistration" \
	--append translationShortDescription='"de_DE" "Selbst-Deregistrierung"' \
	--append translationShortDescription='"fr_FR" "Auto-désinscription"' \
	--set longDescription="This attribute indicates whether a user has requested to deregister his account." \
	--append translationLongDescription='"de_DE" "Dieses Attribut zeigt an, ob sich ein User selbst über das Self-Service-Modul deregistriert hat."' \
	--append translationLongDescription='"fr_FR" "Cet attribut indique si un utilisateur ou une utilisatrice a demandé sa désinscription."' \
	--set tabAdvanced=0 \
	--set tabName="Password recovery" \
	--append translationTabName='"de_DE" "Passwort-Wiederherstellung"' \
	--append translationTabName='"fr_FR" "Réinitialisation du mot de passe"' \
	--set module="users/user" \
	--set syntax="TrueFalseUpper" \
	--set multivalue=0 \
	--set valueRequired=0 \
	--set mayChange=1 \
	--set doNotSearch=0 \
	--set objectClass=univentionPasswordSelfService \
	--set ldapMapping=univentionDeregisteredThroughSelfService \
	--set deleteObjectClass=0 \
	--set overwriteTab=0 \
	--set fullWidth=1 || die

udm settings/extended_attribute create "$@" --ignore_exists \
	--position "cn=custom attributes,cn=univention,$ldap_base" \
	--set name="UniventionDeregistrationTimestamp" \
	--set CLIName="DeregistrationTimestamp" \
	--set shortDescription="Deregistration timestamp" \
	--append translationShortDescription='"de_DE" "Deregistrierungs-Timestamp"' \
	--append translationShortDescription='"fr_FR" "Horodatage de la désinscription"' \
	--set longDescription="Timestamp of the moment the user requested deregistration of his account" \
	--append translationLongDescription='"de_DE" "Zeitstempel des Zeitpunkts, zu dem der Benutzer die Abmeldung seines Kontos beantragt hat."' \
	--append translationLongDescription='"fr_FR" "Horodatage de l’instant auquel l’utilisateur ou l’utilisatrice a demandé sa désinscription."' \
	--set tabAdvanced=0 \
	--set tabName="Password recovery" \
	--append translationTabName='"de_DE" "Passwort-Wiederherstellung"' \
	--append translationTabName='"fr_FR" "Réinitialisation du mot de passe"' \
	--set module="users/user" \
	--set syntax="string" \
	--set multivalue=0 \
	--set valueRequired=0 \
	--set mayChange=1 \
	--set doNotSearch=0 \
	--set objectClass=univentionPasswordSelfService \
	--set ldapMapping=univentionDeregistrationTimestamp \
	--set deleteObjectClass=0 \
	--set overwriteTab=0 \
	--set fullWidth=1 || die

udm settings/usertemplate create "$@" --ignore_exists \
	--position "cn=templates,cn=univention,$ldap_base" \
	--set name="selfserviceregistrationtemplate" \
	--set displayName="<firstname> <lastname><:strip>" \
	--set unixhome="/home/<username>" \
	--set primaryGroup="cn=Domain Users,cn=groups,$ldap_base" \
	--set shell="/bin/bash" || die

udm container/cn create "$@" --ignore_exists \
	--position "$ldap_base" \
	--set name="self registered users" \
	--set userPath="1" || die

univention-config-registry set \
	"umc/self-service/account-registration/frontend/enabled?false" \
	"umc/self-service/account-registration/usertemplate?cn=selfserviceregistrationtemplate,cn=templates,cn=univention,$ldap_base" \
	"umc/self-service/account-registration/usercontainer?cn=self registered users,$ldap_base" \
	"umc/self-service/account-registration/udm_attributes?firstname,lastname,username" \
	"umc/self-service/account-registration/udm_attributes/required?lastname,username" \
	"umc/self-service/account-verification/frontend/enabled?false" \
	"umc/self-service/account-verification/next-steps?Continue to the <a href='/univention/portal'>Univention Portal</a>." \
	"umc/self-service/account-verification/next-steps/de?Weiter zum <a href='/univention/portal'>Univention Portal</a>." \
	"umc/self-service/account-deregistration/enabled?false"

umc_init
umc_operation_create "passwordreset-all" "Password reset service" "" "passwordreset/*"
udm policies/umc modify "$@" \
	--dn "cn=selfservice-umc-servers,cn=UMC,cn=policies,$ldap_base" \
	--append "allow=cn=passwordreset-all,cn=operations,cn=UMC,cn=univention,$ldap_base"

stop_udm_cli_server

joinscript_save_current_version

exit 0
