#!/bin/sh

set -ue
PATH="/usr/bin:/bin"
export PATH

URL="http://127.0.0.1/roundcube/"
sed -ri 's,^\s*#\s*(Alias\s+/roundcube/?\s),\1,' /etc/roundcube/apache.conf
systemctl reload apache2.service

# staple a random string to the login page so we can check we get the right page later
SEED="$(head -c18 /dev/urandom | base64)"
cat >>"/etc/roundcube/config.inc.php" <<-EOF
	\$config['support_url'] = 'mailto:noreply@example.net?subject=$SEED';
EOF

# make sure we get a working login page (and that it contains the seed)
OUT="$(mktemp --tmpdir="$AUTOPKGTEST_TMP")"
if ! code="$(curl -fsS -o "$OUT" -w"%{http_code}" "$URL")" || [ $code -ne 200 ]; then
    echo "Got HTTP code $code (wanted 200)" >&2
    exit 1
elif ! grep -Fq -e "$SEED" <"$OUT" || ! grep -Fqw "rcmloginsubmit" <"$OUT"; then
    echo ">>>" >&2
    cat <"$OUT" >&2
    echo "<<<" >&2
    echo "Landing page is lacking seed or login button!" >&2
    exit 1
fi

# run installer/check.php
ln -sT /usr/share/roundcube/installer /var/lib/roundcube/public_html/installer

if ! code="$(curl -fsS -o "$OUT" -w"%{http_code}" "${URL%/}/installer/")" || [ $code -ne 200 ]; then
    echo "Got HTTP code $code (wanted 200)" >&2
    exit 1
elif grep -Fq "your webserver does not meet the requirements" <"$OUT" || \
        ! grep -Eq '<input type="submit" value="NEXT"\s*/>' <"$OUT"; then
    echo ">>>" >&2
    cat <"$OUT" >&2
    echo "<<<" >&2
    echo "installer/check.php failed!" >&2
    exit 1
fi

rm -f /var/lib/roundcube/public_html/installer

exit 0
