#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: "Write access to a share with sambaWriteable=No"
## exposure: safe
## packages:
##  - univention-samba | univention-samba4
## roles:
## - domaincontroller_master
## - domaincontroller_backup
## - domaincontroller_slave
## - memberserver
## tags:
## - skip_admember

# shellcheck source=../../lib/user.sh
. "$TESTLIBPATH/user.sh" || exit 137
# shellcheck source=../../lib/shares.sh
. "$TESTLIBPATH/shares.sh" || exit 137
# shellcheck source=../../lib/random.sh
. "$TESTLIBPATH/random.sh" || exit 137
# shellcheck source=../../lib/samba.sh
. "$TESTLIBPATH/samba.sh" || exit 137
. /usr/share/univention-lib/ldap.sh || exit 137

kdestroy || true # see Bug 52130

listener_replication_sleep_seconds=1
listener_replication_retry_max=30

echo "## create user"
SAMBA="true"
MAIL="false"
KERBEROS="true"
PERSON="false"
POSIX="true"

username="$(user_randomname)"
password=univention
sharename="$(random_share)"

trap 'user_remove "$username";share_remove "$sharename";wait_for_replication_and_postrun; rm -rf "/${sharename:?}";' INT TERM EXIT
if ! user_create "$username"; then
	fail_fast 1 "Could not create user $username."
fi

SHARE_SAMBA_WRITEABLE=0

echo "## create share"
share_create "$sharename" "/$sharename"
if [ "$?" != 0 ]; then
	fail_fast 1 "could not create share"
fi

wait_for_replication_and_postrun

if dpkg -s univention-samba4 2>&1 | grep "install ok installed" > /dev/null; then
# force_drs_replication
	wait_for_drs_replication "(sAMAccountName=$username)"
fi

sleep 10
admin_account="$(ucs_convertDN2UID "$tests_domainadmin_account")"

echo "## wait for samba share export"
i=0
while ! output="$(smbclient -U "$admin_account%$tests_domainadmin_pwd" "//$hostname.$domainname/$sharename" -c "exit" 2>&1)"
do
	let i="$i"+1
	if [ "$i" = "$listener_replication_retry_max" ]; then
		echo "$output"
		fail_fast 1 "TIMEOUT: Samba did not export the share '$sharename' after $((i * $listener_replication_sleep_seconds)) seconds"
	fi
	sleep "$listener_replication_sleep_seconds"
done

echo "## Try to create a folder in a share with sambaWriteable=No"
output="$(smbclient -U "$username%$password" "//$hostname.$domainname/$sharename" -c "mkdir folder1" 2>&1)"
echo "$output" | egrep -q "(NT_STATUS_MEDIA_WRITE_PROTECTED|NT_STATUS_ACCESS_DENIED)"
if [ "$?" != 0 ]; then
	fail_test 1 "Expected return value (NT_STATUS_MEDIA_WRITE_PROTECTED|NT_STATUS_ACCESS_DENIED), but received: $output"
fi

exit "$RETVAL"
