#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Simulate an UCS import including password change from UCS to AD in sync-mode"
## exposure: dangerous
## tags:
##  - basic
## packages:
## - univention-s4-connector

# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137
# shellcheck source=../../lib/udm.sh
. "$TESTLIBPATH/udm.sh" || exit 137
# shellcheck source=../../lib/random.sh
. "$TESTLIBPATH/random.sh" || exit 137

. "s4connector.sh" || exit 137
test -n "$connector_s4_ldap_host" || exit 137
connector_running_on_this_host || exit 137

SYNCMODE="$(ad_get_sync_mode)"
ad_set_sync_mode "sync"
invoke-rc.d univention-s4-connector restart

# Make some import rounds with an increasing sleep time before changing the password
for i in 0 3 6 12; do
	UDM_users_user_lastname="$(random_chars)"
	UDM_users_user_password="U$(random_chars)123"

	B00="$(random_chars)"
	B01="$(random_chars)"
	B02="$(random_chars)"
	B03="$(random_chars)"
	B04="$(random_chars)"

	UDM_B00_DN="uid=$B00,cn=users,$ldap_base"
	UDM_B01_DN="uid=$B01,cn=users,$ldap_base"
	UDM_B02_DN="uid=$B02,cn=users,$ldap_base"
	UDM_B03_DN="uid=$B03,cn=users,$ldap_base"
	UDM_B04_DN="uid=$B04,cn=users,$ldap_base"

	for b in "$B00" "$B01" "$B02" "$B03" "$B04"; do
		UDM_users_user_username="$b"
		# udm_create "users/user" || fail_test 110
		udm_create "users/user" "" "" "" "" || fail_test 110
		sleep $i
		udm users/user modify --dn "uid=$b,cn=users,$ldap_base" --set password=q1w2e3r4 || fail_test 110
	done

	ad_wait_for_synchronization; fail_bool 0 110

	for b in "$B00" "$B01" "$B02" "$B03" "$B04"; do
		echo "Search in UCS LDAP as user $b with the new password"
		univention-ldapsearch -D "uid=$b,cn=users,$ldap_base" -w q1w2e3r4 -LLL -s base dn || fail_test 110
		echo "Search in AD as user $b with the new password"
		univention-s4search -U "$b"%q1w2e3r4 -s base dn || fail_test 110
	done

	section "Clean up"

	for b in "$B00" "$B01" "$B02" "$B03" "$B04"; do
		UDM_users_user_username="$b"
		udm_remove "users/user" || fail_test 110
	done

	ad_wait_for_synchronization; fail_bool 0 110

	for b in "$B00" "$B01" "$B02" "$B03" "$B04"; do
		UDM_users_user_username="$b"
		udm_exists "users/user"; fail_bool 1 110
	done
done

ad_set_sync_mode "$SYNCMODE"

exit "$RETVAL"
