#!/usr/share/ucs-test/runner bash
## desc: Create egroupware users and test the login
## tags:
##  - apptest
## exposure: dangerous

. "$TESTLIBPATH/base.sh" || exit 137
. "$TESTLIBPATH/user.sh" || exit 137
. "$TESTLIBPATH/random.sh" || exit 137
. "/usr/share/univention-lib/all.sh" || exit 137

eval "$(/usr/sbin/ucr shell)"

RETVAL=100

create_egroupware_user () {
	local username=$1
	udm-test users/user create \
		--position "cn=users,$ldap_base" \
		--set username="$username" \
		--set firstname="$(random_string)" \
		--set lastname="$(random_string)" \
		--set password="univention" \
		--append groups="cn=Default,cn=groups,$ldap_base"
}

change_password ()
{
	local username="$1"
	local new_password="$2"
	udm-test users/user modify \
		--dn "uid=$username,cn=users,$ldap_base" \
		--set password="$new_password"
}

egroupware_login () {
	local username="$1"
	local password="$2"
	local proto="${3:-http}"
	local data="passwd_type=text&account_type=u&logindomain=default&login=$username&passwd=$password&submitit=++Anmelden++"
	local cookies=$(mktemp)
	local url="$proto://$hostname.$domainname/egroupware/login.php"
	curl --cacert /etc/univention/ssl/ucsCA/CAcert.pem -c "$cookies" -s --data "$data" "$url"
	grep -q "last_loginid.*$username" "$cookies"
	return $?
}

active_sync () {
	local username="$1"
	local password="$2"
	local proto="${3:-http}"
	local url="$proto://$hostname.$domainname/Microsoft-Server-ActiveSync"
	wget --ca-certificate=/etc/univention/ssl/ucsCA/CAcert.pem --user "$username" --password="$password" "$url"
	return $?
}

username1="egroupware1"
username2="egroupware2"
create_egroupware_user "$username1"
create_egroupware_user "$username2"
wait_for_replication

set -x

# standard
egroupware_login "$username1" "univention" || fail_test 110 "Login was denied"
egroupware_login "$username1" "univention123" && fail_test 110 "Login with wrong password"
egroupware_login "$username2" "univention" || fail_test 110 "Login was denied"
egroupware_login "$username2" "univention123" && fail_test 110 "Login with wrong password"

active_sync "$username1" "univention" || fail_test 110 "ActiveSync logon failed"
active_sync "$username1" "univention1" && fail_test 110 "ActiveSync logon with wrong password"
active_sync "$username2" "univention" || fail_test 110 "ActiveSync logon failed"
active_sync "$username2" "univention1" && fail_test 110 "ActiveSync logon with wrong password"

# password change
change_password "$username2" "Univention.99ä"
wait_for_replication
egroupware_login "$username2" "Univention.99ä" || fail_test 110 "login was denied"
egroupware_login "$username2" "univention" && fail_test 110 "login with wrong password"

# https
egroupware_login "$username1" "univention" "https" || fail_test 110 "https login was denied"
active_sync "$username1" "univention" "https" || fail_test 110 "ActiveSync https login was denied"

set +x

user_remove "$username1"
user_remove "$username2"

wait_for_replication

exit $RETVAL
