#!/bin/sh
#
# start_mysqld_and_auto_install.sh - starts an instance of mysqld before
# auto_installing and running do_mysql's test suite. It is inspired by
# debian/test_mysql.sh from libdbi-drivers source package.

set -ex

MYTEMP_DIR=`mktemp -d`

export MYSQL_UNIX_PORT=${MYTEMP_DIR}/mysql.sock
DO_MYSQL_USER=${USER}
DO_MYSQL_DBNAME=test
DO_MYSQL_DATABASE=/${DO_MYSQL_DBNAME}

# Ubuntu: on Debian/MariaDB they use mysql_install_db which defaults to creating
# two DB users, root and a user matching the system user under which the daemon runs.
# MySQL doesn't work that way, so we need to replicate this behaviour manually.

/usr/sbin/mysqld --no-defaults --initialize-insecure --user=${DO_MYSQL_USER} --datadir=${MYTEMP_DIR}
/usr/sbin/mysqld --no-defaults --user=${DO_MYSQL_USER} --socket=${MYSQL_UNIX_PORT} --datadir=${MYTEMP_DIR} --skip-networking &
MYSQL_PID=$!

# Ubuntu: At this point we don't have any user other than root
mysqladmin="/usr/bin/mysqladmin --user=root --socket=${MYSQL_UNIX_PORT}"

echo -n pinging mysqld.
attempts=0
while ! $mysqladmin ping ; do
  sleep 3
  attempts=$((attempts+1))
  if [ ${attempts} -gt 10 ] ; then
    echo "skipping test, mysql server could not be contacted after 30 seconds"
    exit 0
  fi
done

cleanup() {
  $mysqladmin shutdown || kill "${MYSQL_PID}"
  rm -rf ${MYTEMP_DIR}
}
trap cleanup INT EXIT TERM

# Ubuntu: we create the user and grant privilege on ALL databases, not just `test` as the test suite uses others DBs too
mysql --user=root --socket=${MYSQL_UNIX_PORT} --execute "CREATE USER '${DO_MYSQL_USER}'@'localhost'; GRANT ALL PRIVILEGES ON *.* TO '${DO_MYSQL_USER}'@'localhost'; CREATE DATABASE test;"

"$@"
