#!/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

# dbconfig-no-thanks: set custom $config['db_dsnw']
DBNAME="/var/lib/roundcube/database/roundcube.db"
DBMODE=0600
cat >"/etc/roundcube/debian-db-roundcube.php" <<-EOF
	<?php
	\$config['db_dsnw'] = "sqlite:///$DBNAME?mode=$DBMODE";
	?>
EOF

# intentionally fail if the directory already exists
mkdir -m0700 /var/lib/roundcube/database
chown www-data: /var/lib/roundcube/database

# 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

assert_db_stat() {
    local st1="www-data:www-data $DBMODE" st2
    if [ ! -e "$DBNAME" ]; then
        printf "SQLite3 database %s is missing!\n" "$DBNAME" >&2
        exit 1
    elif ! st2="$(stat -c "%U:%G %#a" -- "$DBNAME")" || [ "$st1" != "$st2" ]; then
        printf "%s has ownership/mode \"%s\", expected \"%s\"\\n" "$DBNAME" "$st2" "$st1" >&2
        exit 1
    fi
}

# the first connection should trigger DB creation
assert_db_stat

# manually recreate DB from scratch (updatedb.sh is also used for schema upgrades)
rm -f -- "$DBNAME"
/sbin/runuser -u www-data -- /usr/share/roundcube/bin/updatedb.sh \
    --package=roundcube --dir=/usr/share/roundcube/SQL
assert_db_stat

exit 0
