#!/bin/sh

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

URL="http://127.0.0.1/roundcube/"

# 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

# lighttpd uses /run/php/php-fpm.sock
# https://sources.debian.org/src/lighttpd/sid/debian/conf-available/15-fastcgi-php-fpm.conf
PHP_VERSION="$(php -r 'echo join(".",[PHP_MAJOR_VERSION, PHP_MINOR_VERSION]);')"
[ -S /run/php/php-fpm.sock ] || ln -sT "php$PHP_VERSION-fpm.sock" /run/php/php-fpm.sock

# make sure we get a working login page (and that it contains the seed)
OUT="$(mktemp --tmpdir)"
if ! code="$(curl -fsS -o "$OUT" -w"%{http_code}" "$URL")" || [ $code -ne 200 ]; then
    echo "Got HTTP code $code (wanted 200)" >&2
    exit 1
fi

if ! 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

# make sure we were using PHP-FPM and not the CGI binary
systemctl stop "php$PHP_VERSION-fpm.service"
if code="$(curl -fso/dev/null -w"%{http_code}" "$URL")" || [ $code -ne 503 ]; then
    echo "Got HTTP code $code (wanted 503)" >&2
    exit 1
fi

# now purge roundcube-core
DEBIAN_FRONTEND="noninteractive" apt-get remove --purge -y roundcube-core 2>&1
if ls -l /etc/lighttpd/conf-enabled/*-roundcube.conf 2>/dev/null; then
    echo "Didn't run \`lighty-disable-mod roundcube\` on purge!" >&2
    exit 1
fi

# and finally reinstall with a pre-enabled PHP-CGI (to check for #988236 regressions)
lighty-disable-mod fastcgi-php-fpm
lighty-enable-mod fastcgi-php
DEBIAN_FRONTEND="noninteractive" apt-get install --no-install-recommends -y roundcube-core 2>&1

if ! code="$(curl -fsSo/dev/null -w"%{http_code}" "$URL")" || [ $code -ne 200 ]; then
    echo "Got HTTP code $code (wanted 200)" >&2
    exit 1
fi

# make sure we were using the CGI binary
lighty-disable-mod fastcgi-php
systemctl reload lighttpd.service
if code="$(curl -fso/dev/null -w"%{http_code}" "$URL")" && [ $code -eq 200 ]; then
    echo "Got HTTP code $code (wanted ~200)" >&2
    exit 1
fi

exit 0
