#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: Check listener functionality
## tags:
##  - basic
##  - apptest
##  - replication
## roles-not: [basesystem]
## packages:
##  - univention-directory-listener
## exposure: dangerous

# shellcheck source=../../lib/base.sh
. "$TESTLIBPATH/base.sh" || exit 137
# shellcheck source=../../lib/user.sh
. "$TESTLIBPATH/user.sh" || exit 137
# shellcheck source=../../lib/maildomain.sh
. "$TESTLIBPATH/maildomain.sh" || exit 137
# shellcheck source=../../lib/undo.sh
. "$TESTLIBPATH/undo.sh" || exit 137

tempFile="$(mktemp)"
undo rm -f "$tempFile"

ucstest="ucstest_$(random_chars)"
listener="/usr/lib/univention-directory-listener/system/$ucstest.py"
cat >"$listener" <<__HERE__
import listener
description = 'set up a new handler (with an new uid entry in tmp-file) for listener'
name = 'ucstest'
filter = '(objectClass=posixAccount)'

def handler(dn, new, old):
	if new:
		listener.setuid(0)
		with open("$tempFile", 'a+') as fd:
			fd.write('New User: %s\n' % (new['uid'][0].decode('UTF-8'),))
		listener.unsetuid()
__HERE__
undo systemctl restart univention-directory-listener # Reversed order
undo rm -f "$listener"
systemctl restart univention-directory-listener

# create domain part in configured mail domains list
create_mail_domain "$domainname" && undo delete_mail_domain "$domainname"

USERNAME=$(user_randomname)
user_create "$USERNAME" &&
	undo user_remove "$USERNAME" ||
	fail_fast 1 "Failed to create user $USERNAME"

wait_for_replication

if grep "New User: $USERNAME" "$tempFile"
then
	echo "Found username '$USERNAME' in tempfile '$tempFile'"
else
	fail_test 1 "Did not find username '$USERNAME' in tempfile '$tempFile'"
fi

exit "$RETVAL"
