#!/bin/bash
set -ex

if ! sudo test -d /var/lib/mysql/mysql; then
    sudo mysqld --initialize-insecure --user=mysql
fi

sudo install -d -o mysql -g mysql -m 0755 /var/run/mysqld

sudo tee /var/run/mysqld/init.sql > /dev/null <<'SQL'
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'om';
CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY 'om';
ALTER USER 'root'@'%' IDENTIFIED WITH caching_sha2_password BY 'om';
GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION;
CREATE USER IF NOT EXISTS 'om'@'%' IDENTIFIED BY 'om';
ALTER USER 'om'@'%' IDENTIFIED WITH caching_sha2_password BY 'om';
SQL

# --skip-log-error overrides the packaged config's log_error file and sends the error log to stderr instead. dumb-init
# rewrites SIGINT to SIGTERM, as mysqld ignores SIGINT but shuts down cleanly on SIGTERM.
exec sudo dumb-init --rewrite 2:15 mysqld --user=mysql --init-file=/var/run/mysqld/init.sql --skip-log-error
