#!/bin/sh

set -eu

# Needed to find lighttpd binary and the chromedriver binary
export PATH="/sbin:/usr/sbin:/usr/bin:$PATH"
MARIADB_DIR="$AUTOPKGTEST_TMP/db-data"
MARIADB_DATA="$MARIADB_DIR/data"
MARIADB_PIDFILE="$MARIADB_DIR/run/mysql.pid"
MARIADB_UNIX_SOCKET="$MARIADB_DIR/run/mysql.sock"

if [ -d "$MARIADB_DIR" ]; then
    sudo rm -rf $MARIADB_DIR
fi

mkdir -p "$MARIADB_DATA"
mkdir "$MARIADB_DIR/run"
sudo chown mysql:mysql -R "$MARIADB_DIR"

echo "Setup the database server..."
sudo -u mysql mariadb-install-db --user=mysql --no-defaults --auth-root-socket-user=system --datadir=${MARIADB_DATA} --force --skip-name-resolve 1>/dev/null 2>/dev/stdout
sudo -u mysql mysqld --skip-networking=ON --user=mysql --socket=${MARIADB_UNIX_SOCKET} --datadir=${MARIADB_DATA} --pid-file=${MARIADB_PIDFILE} --explicit_defaults_for_timestamp 1>/dev/null 2>/dev/stdout &
MARIADB_PID=$!
# Wait for DB to start
echo "Waiting for the database to start"
sleep 20

echo "Setup the database user & db..."
echo "CREATE USER IF NOT EXISTS 'matomo-user'@'localhost' IDENTIFIED VIA 'mysql_native_password' USING PASSWORD('MatomoP@ssw0rd');" > $AUTOPKGTEST_TMP/db_setup.sql
echo "CREATE DATABASE IF NOT EXISTS \`matomo-db\`;" >> $AUTOPKGTEST_TMP/db_setup.sql
echo "GRANT CREATE, ALTER, SELECT, INSERT, UPDATE, DELETE, DROP, CREATE TEMPORARY TABLES ON \`matomo-db\`.* TO 'matomo-user'@'localhost';" >> $AUTOPKGTEST_TMP/db_setup.sql

sudo -u root mysql --socket=${MARIADB_UNIX_SOCKET} < $AUTOPKGTEST_TMP/db_setup.sql
rm $AUTOPKGTEST_TMP/db_setup.sql

chromedriver --version

echo "Setup the webserver..."
PORT=8888
DOCROOT="$AUTOPKGTEST_TMP/docroot"
CONF="$AUTOPKGTEST_TMP/lighttpd.conf"
APP_CONF="$AUTOPKGTEST_TMP/lighttpd_matomo.conf"
mkdir -p "$DOCROOT"

# Make a socket folder
if [ ! -d "$AUTOPKGTEST_TMP/run/" ]; then
    mkdir "$AUTOPKGTEST_TMP/run/"
fi

sudo chown www-data:www-data "$AUTOPKGTEST_TMP/run/"

# Remove this when postinst is implemented
cp debian/conf/lighttpd.conf "$APP_CONF"
cat >"$CONF" <<EOF
server.document-root = "$DOCROOT"
server.port = $PORT
server.modules = ( "mod_access", "mod_auth", "mod_fastcgi", "mod_alias" )
fastcgi.server += ( ".php" =>
        ((
                "bin-path" => "/usr/bin/php-cgi",
                "socket" => "$AUTOPKGTEST_TMP/run/php.socket",
                "max-procs" => 1,
                "bin-environment" => (
                        "PHP_FCGI_CHILDREN" => "4",
                        "PHP_FCGI_MAX_REQUESTS" => "10000"
                ),
                "bin-copy-environment" => (
                        "PATH", "SHELL", "USER"
                ),
                "broken-scriptfilename" => "enable"
        ))
)
include "$APP_CONF"
mimetype.assign   += ( ".html" => "text/html", ".css" => "text/css", ".php" => "application/php" )
index-file.names            = ( "index.php" )
static-file.exclude-extensions = ( ".php" )

EOF

# validate test configuration
lighttpd -tt -f "$CONF"

sudo -u www-data lighttpd -D -f "$CONF" 2>/dev/stdout &
LIGHTTPD_PID=$!
rm -f $AUTOPKGTEST_TMP/run/php.socket

cleanup() {
    if [ -f /usr/share/matomo/config/config.ini.php ]; then
        echo "Removing the config file"
        sudo -u www-data rm /usr/share/matomo/config/config.ini.php
    fi
    echo "Stopping daemons..."
    kill "$LIGHTTPD_PID" || echo "Unable to kill lighttpd"
    kill "$MARIADB_PID" || echo "Unable to kill mariadb-server"
}

trap cleanup EXIT

if [ -f /usr/share/matomo/config/config.ini.php ]; then
    echo "Removing the config file before tests, backup is at: /usr/share/matomo/config/config.ini.php.bak"
    sudo -u www-data mv /usr/share/matomo/config/config.ini.php /usr/share/matomo/config/config.ini.php.bak
fi

echo "Run tests..."
# Allow commands to fail
set +e

# Wait a bit for things to stale
sleep 5
# Do tests
# Send to stdout (https://bugs.python.org/issue16164)
MARIADB_UNIX_SOCKET="${MARIADB_UNIX_SOCKET}" python3 ./debian/tests/test_matomo_web.py  2>/dev/stdout

EXIT_CODE=$?
if [ "$EXIT_CODE" -ne "0" ]; then
    echo "Tests failed !"
fi

exit $EXIT_CODE
