#!/bin/bash

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

set -x
set -e

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

ucs_parseCredentials "$@"

test -n "$binddn" || false
test -n "$bindpwdfile" || false

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

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

remove_user () {
	udm users/user remove \
		--binddn "$binddn" \
		--bindpwdfile "$bindpwdfile" \
        	--dn "uid=$1,cn=users,$ldap_base"
}

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 -c "$cookies" -v --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 --user "$username" --password="$password" "$url"
	return $?
}

die () {
	echo "$1" >&2
	exit 1
}

username1="egroupware1"
username2="egroupware2"

trap "{ 
	remove_user "$username1"
	remove_user "$username2"
}" EXIT

create_egroupware_user "$username1"
create_egroupware_user "$username2"

sleep 10 # wait_for_replication

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

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

# password change
change_password "$username2" "Univention.99ä"

sleep 10 # wait_for_replication
docker exec egroupware kill -s usr2 1

egroupware_login "$username2" "Univention.99ä" || die "login was denied"
egroupware_login "$username2" "univention" && die "login with wrong password"

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

exit 0