#!/bin/bash

# test database cleanup and garbage collection routines

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

# program/lib/Roundcube/bootstrap.php
RCUBE_TEMP_FILE_PREFIX="RCMTEMP"
RCUBE_INSTALL_PATH="/var/lib/roundcube"
DBNAME="roundcube"
RV=0

# make sure suggested hardening options don't break roundcube-*.service
mkdir /etc/systemd/system/roundcube-cleandb.service.d /etc/systemd/system/roundcube-gc.service.d
cat >/etc/systemd/system/roundcube-cleandb.service.d/override.conf <<-EOF
	[Service]
	ProtectSystem=strict
	RestrictAddressFamilies=AF_UNIX
EOF
cp /etc/systemd/system/roundcube-cleandb.service.d/override.conf \
   /etc/systemd/system/roundcube-gc.service.d/override.conf
systemctl daemon-reload


# check bin/cleandb.sh (remove old records that were marked as deleted)
mysql "$DBNAME" <<-EOF
	INSERT INTO \`users\`
	  (\`user_id\`, \`username\`, \`mail_host\`, \`created\`)
	    VALUES
	  (1, 'user', '127.0.0.1', NOW());
	INSERT INTO \`identities\`
	  (\`user_id\`, \`changed\`, \`del\`, \`name\`, \`email\`)
	    VALUES
      (1, NOW(), 0, 'Foo Bar', 'noreply@example.net'),
	  (1, DATE_SUB(NOW(), INTERVAL 1 MONTH), 1, 'Foo Bar', 'deleted@example.net');
EOF

NOW="$(date +%s.%N)"
systemctl --wait start roundcube-cleandb.service

OUT="$(mktemp --tmpdir="$AUTOPKGTEST_TMP")"
journalctl --output=cat --since="@$NOW" -u roundcube-cleandb.service >"$OUT"
count_identities="$(mysql -N "$DBNAME" <<<"SELECT COUNT(*) FROM identities")"
if ! grep -Eq "^1 records? deleted from 'identities'$" <"$OUT" || [ $count_identities -ne 1 ]; then
    echo "Failed to run cleandb.sh?" >&2
    mysql -t "$DBNAME" >&2 <<<"SELECT * FROM identities ORDER BY user_id, changed"
    cat <"$OUT" >&2
    RV=1
fi


# check bin/gc.sh (purge expired sessions, caches and tempfiles)
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

connections=10
for ((i=1; i < $connections; i++)); do
    if ! code="$(curl -fsS -o/dev/null --interface "127.0.0.$i" -w"%{http_code}" "$URL")" || [ $code -ne 200 ]; then
        echo "Got HTTP code $code (wanted 200)" >&2
        exit 1
    fi
done
curl -fsS -o/dev/null "$URL" # one more from 127.0.0.1

count_sessions="$(mysql -N "$DBNAME" <<<"SELECT COUNT(*) FROM session")"
if [ $count_sessions -ne $connections ]; then
    echo "Got $count_sessions sessions, expected $connections" >&2
    mysql -t "$DBNAME" >&2 <<<"SELECT * FROM session ORDER BY ip, changed"
    exit 1
fi

mysql -t "$DBNAME" <<-EOF
	UPDATE session SET changed = DATE_SUB(changed, INTERVAL 30 MINUTE)
      WHERE ip >= '127.0.0.1' AND ip < '127.0.0.5'
EOF

# $config['temp_dir_ttl'] defaults to '48h' with a 6h lower bound
touch -d "last year"                       "$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}00"
touch -d "$((48 * 3600 + 1)) seconds ago"  "$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}01"
touch -d "$((48 * 3600 - 60)) seconds ago" "$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}02"
touch                                      "$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}03"
touch -d "tomorrow"                        "$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}04"

systemctl --wait start roundcube-gc.service

count_sessions="$(mysql -N "$DBNAME" <<<"SELECT COUNT(*) FROM session")"
if [ $count_sessions -ne 5 ]; then
    echo "Got $count_sessions sessions, expected $connections" >&2
    mysql -t "$DBNAME" >&2 <<<"SELECT * FROM session ORDER BY ip"
    RV=1
fi

for i in 00 01; do
    p="$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}${i}"
    if test -e "$p"; then
        echo "$p was not deleted!" >&2
        RV=1
    fi
done
for i in 02 03 04; do
    p="$RCUBE_INSTALL_PATH/temp/${RCUBE_TEMP_FILE_PREFIX}${i}"
    if ! test -e "$p"; then
        echo "$p was deleted!" >&2
        RV=1
    fi
done

exit $RV
