#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Create an UCS-User and check password in write-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

UDM_users_user_username="$(random_chars)"
UDM_users_user_lastname="$(random_chars)"
# If the password doesn't adhere the configured Windows-Password-Guidelines
# weird things might happen when the user is synced to AD.
UDM_users_user_password="U$(random_chars)123"
UDM_users_user_firstname="$(random_chars)"
AD_DN="CN=$UDM_users_user_username,CN=users,$(ad_get_base)"

SYNCMODE="$(ad_get_sync_mode)"

ad_set_sync_mode "write"

udm_create "users/user" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

section "Trying authentication"

HOST="$(ucr get connector/ad/ldap/host)"

smbclient //"${HOST}"/sysvol -c ls -U "${UDM_users_user_username}%${UDM_users_user_password}" ; fail_bool 0 100

section "Trying authentication with wrong password"

smbclient //"${HOST}"/sysvol -c ls -U "${UDM_users_user_username}%${UDM_users_user_password}1" ; fail_bool 1 100

section "Change password"

UDM_users_user_password="A$(random_chars)22"
udm_modify "users/user" "" "" "" "" \
	--set password="$UDM_users_user_password" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

section "Trying authentication second time"

smbclient //"${HOST}"/sysvol -c ls -U "${UDM_users_user_username}%${UDM_users_user_password}1" ; fail_bool 0 100

section "Change password to contain umlauts"

UDM_users_user_password="Äü$(random_chars)ß22"
udm_modify "users/user" "" "" "" "" \
	--set password="$UDM_users_user_password" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

section "Trying authentication third time"

smbclient //"${HOST}"/sysvol -c ls -U "${UDM_users_user_username}%${UDM_users_user_password}1" ; fail_bool 0 100

udm_remove "users/user" || fail_test 110
ad_wait_for_synchronization; fail_bool 0 110

udm_exists "users/user"; fail_bool 1 110
ad_exists "$AD_DN"; fail_bool 1 110

ad_set_sync_mode "$SYNCMODE"

exit "$RETVAL"
