#!/bin/bash

VERSION="2"

. /usr/share/univention-appcenter/joinscripthelper.sh

eval "$(ucr shell)"

joinscript_init

ucs_addServiceToLocalhost "${SERVICE}" "$@"

container_port="$(ucr get appcenter/apps/qd-consent/ports/8443)"

apache_cfg="/etc/apache2/ucs-sites.conf.d/qd-consent.conf"

cat > "$apache_cfg" << "EOF"
# Warning: This file is auto-generated by qd-consent. Do not alter.
EOF

echo "ProxyRequests Off" >> "$apache_cfg"
echo "ProxyVia On" >> "$apache_cfg"
echo "RewriteEngine On" >> "$apache_cfg"
echo "RewriteCond %{HTTP:Connection} Upgrade [NC]" >> "$apache_cfg"
echo "RewriteCond %{HTTP:Upgrade} websocket [NC]" >> "$apache_cfg"
echo "RewriteRule ^/qd-consent/?(.*) \"ws://127.0.0.1:$container_port/qd-consent/\$1\" [P,L]" >> "$apache_cfg"
echo "ProxyPass /qd-consent http://127.0.0.1:$container_port/qd-consent retry=0"  >> "$apache_cfg"
echo "ProxyPassReverse /qd-consent http://127.0.0.1:$container_port/qd-consent" >> "$apache_cfg"

a2enmod proxy proxy_http proxy_wstunnel

service apache2 reload

joinscript_save_current_version

exit 0