#!/usr/share/ucs-test/runner bash
# shellcheck shell=bash
## desc: Test UCS' Apache2 VHost integration
## bugs: [45115]
## tags: [skip_admember]
## packages:
##  - univention-ssl
##  - univention-apache-vhost
## exposure: dangerous
set -e -x

# this would be part of the app installation
DIR="/var/lib/univention-appcenter/apps/myapp/data"
APACHE_DIR="/var/www/html/myapp/"
mkdir -p "$DIR"
mkdir -p "$APACHE_DIR"

echo "DocumentRoot $APACHE_DIR" > "$DIR/apache.conf"
echo "OK" > "$APACHE_DIR/index.html"

# this would be the join script
LOCAL_FQDN="$(ucr get hostname)"."$(ucr get domainname)"
HOST="myapp.$LOCAL_FQDN"
univention-add-vhost "$HOST" 80 --conffile "$DIR/apache.conf" --binddn="$(ucr get tests/domainadmin/account)" --bindpwdfile="$(ucr get tests/domainadmin/pwdfile)"
host "$HOST" || exit 1

# and this is the actual test
for i in $(seq 1 3); do
	ANSWER="$(curl http://"$HOST"/ || true)"
	[ "$ANSWER" = "OK" ] && break
	sleep 3
done
[ "$ANSWER" = "OK" ] || exit 1

# now with HTTPS...
univention-add-vhost "$HOST" 443 --conffile "$DIR/apache.conf" --binddn="$(ucr get tests/domainadmin/account)" --bindpwdfile="$(ucr get tests/domainadmin/pwdfile)"
for i in $(seq 1 3); do
	ANSWER="$(curl https://"$HOST"/ || true)"
	[ "$ANSWER" = "OK" ] && break
	sleep 3
done
[ "$ANSWER" = "OK" ] || exit 1

# ... check certificate
univention-ldapsearch -b "cn=Wildcard Certificate,cn=services,cn=univention,$(ucr get ldap/base)"
CERT_IN_UDM="$(univention-ldapsearch -b "$(ucr get ldap/hostdn)" univentionService | grep "Wildcard Certificate" -c)"
[ "$CERT_IN_UDM" = "1" ] || exit 1

ls /etc/univention/ssl/\*."$LOCAL_FQDN"/ || exit 1

# now with HTTPS, but custom port and without a DNS
univention-add-vhost "*" 20550 --ssl --conffile "$DIR/apache.conf" --binddn="$(ucr get tests/domainadmin/account)" --bindpwdfile="$(ucr get tests/domainadmin/pwdfile)"
for i in $(seq 1 3); do
	ANSWER="$(curl https://"$LOCAL_FQDN":20550/ || true)"
	[ "$ANSWER" = "OK" ] && break
	sleep 3
done
[ "$ANSWER" = "OK" ] || exit 1

# this would be part of the app UNinstallation
# this test better succeeds, or we leave this...
# but strangely, the test fails when used in trap EXIT
rm -r "$DIR"
rm -r "$APACHE_DIR"
univention-add-vhost "*" 20550 --remove --binddn="$(ucr get tests/domainadmin/account)" --bindpwdfile="$(ucr get tests/domainadmin/pwdfile)" --dont-reload-services
univention-add-vhost "$HOST" 80 --remove --binddn="$(ucr get tests/domainadmin/account)" --bindpwdfile="$(ucr get tests/domainadmin/pwdfile)" --dont-reload-services
univention-add-vhost "$HOST" 443 --remove --binddn="$(ucr get tests/domainadmin/account)" --bindpwdfile="$(ucr get tests/domainadmin/pwdfile)"
set +e
host "$HOST" && exit 1
exit 0
