#!/bin/sh

# upstream installer checks

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

# enable installer
ln -sT /usr/share/roundcube/installer /var/lib/roundcube/public_html/installer
cat >>"/etc/roundcube/config.inc.php" <<-EOF
	\$config['enable_installer'] = true;
EOF

OUT="$(mktemp --tmpdir="$AUTOPKGTEST_TMP")"

echo "Step 1: check environment"
if ! code="$(curl -fsS -o "$OUT" -w"%{http_code}" "${URL%/}/installer/?_step=1")" || [ $code -ne 200 ]; then
    echo "Got HTTP code $code (wanted 200)" >&2
    exit 1
elif grep -Fiq -e "your webserver does not meet the requirements" \
               -e "The installer is disabled" \
               -e " class=\"fail\">" \
               <"$OUT" || \
        ! grep -Eiq '<input type="submit" value="NEXT"\s*/>' <"$OUT"; then
    echo ">>>" >&2
    cat <"$OUT" >&2
    echo "<<<" >&2
    echo "/installer/?_step=1 failed!" >&2
    exit 1
fi

# skip step 2 (create config)

echo "Step 3: test config"
if ! code="$(curl -fsS -o "$OUT" -w"%{http_code}" "${URL%/}/installer/?_step=3")" || [ $code -ne 200 ]; then
    echo "Got HTTP code $code (wanted 200)" >&2
    exit 1
elif grep -Eiq "\\sclass=\"fail\"[[:blank:]>]" <"$OUT"; then
    echo ">>>" >&2
    cat <"$OUT" >&2
    echo "<<<" >&2
    echo "/installer/?_step=3 failed!" >&2
    exit 1
fi

exit 0
