#!/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
## packages:
## - univention-ad-connector
## tags:
##  - skip_admember

# 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

. "adconnector.sh" || exit 137
test -n "$connector_ad_ldap_host" || exit 137

. /usr/share/univention-lib/ucr.sh

SYNCMODE="$(ad_get_sync_mode)"
ad_set_sync_mode "sync"
invoke-rc.d univention-ad-connector restart
kdestroy  # to avoid smbclient failure (similar to Bug #52277)

domain=$(ucr get connector/ad/mapping/kerberosdomain)
# use domainname in smbclient call, when samba4 is installed, smbclient seems to have trouble using the correct domain
domain_upper=${domain^^}

# 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
		if is_ucr_true 'connector/ad/mapping/user/password/disabled'; then
			echo "Password sync is disabled, skipping password sync check"
		else
			echo "Search in AD as user $b with the new password"
			smbclient --use-kerberos=no -U "$domain_upper\\$b%q1w2e3r4" //$(ucr get connector/ad/ldap/host)/sysvol -c ls || fail_test 110
		fi
	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

	# TODO: this should be re-activated
	#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"
