#!/bin/sh
# Install MediaWiki on the MySQL backend
# and then verify the installation was successful.
set -e

mkdir /tmp/mw-install
mysql_version=`sudo mysql -NBe 'SELECT @@version;'`
if ! echo "$mysql_version" | grep -q MariaDB && dpkg --compare-versions "$mysql_version" ge 8; then
    # MySQL >= 8 uses caching_sha256_password by default which is not currently
    # supported by PHP's MySQL connector
    echo "CREATE USER 'wikidebadmin'@'localhost' IDENTIFIED WITH 'sha256_password' BY 'DebianIsTheBest';" > /tmp/mw-install/db_setup.sql
else
    echo "CREATE USER 'wikidebadmin'@'localhost' IDENTIFIED BY 'DebianIsTheBest';" > /tmp/mw-install/db_setup.sql
fi
echo "GRANT ALL PRIVILEGES ON * . * TO 'wikidebadmin'@'localhost';" >> /tmp/mw-install/db_setup.sql
sudo mysql < /tmp/mw-install/db_setup.sql
rm /tmp/mw-install/db_setup.sql
php /var/lib/mediawiki/maintenance/install.php --scriptpath /mediawiki --confpath /tmp/mw-install --dbname autopkgtestwiki --dbtype mysql --dbuser wikidebadmin --dbpass DebianIsTheBest --pass DebianIsTheBest Debian-Autopkgtest Administrator
sudo cat >> /tmp/mw-install/LocalSettings.php <<EOF
\$wgShowExceptionDetails = true;
\$wgShowDBErrorBacktrace = true;
ini_set( 'max_execution_time', 300 );
EOF
sudo mv /tmp/mw-install/LocalSettings.php /etc/mediawiki/LocalSettings.php

if [ -f ./debian/tests/install-thing ]; then
    ./debian/tests/install-thing
fi

# Force clearing of PHP caches, etc.
sudo systemctl restart apache2

# Run tests
./debian/tests/assert-cli
./debian/tests/assert-http
if [ -f ./debian/tests/assert-thing ]; then
    ./debian/tests/assert-thing
fi

