#!/usr/bin/env bash

echo 
echo "*** configure MySQL ***"
echo 

yum -y install mariadb-server

systemctl enable  mariadb
systemctl restart mariadb

/usr/bin/mysqladmin -u root password 'passw0rd'

#echo "DELETE FROM user WHERE Host = 'thirdlane.local' and user = 'root';" | /usr/bin/mysql --user=root --password=passw0rd mysql

# add account for service scripts
#echo "GRANT ALL PRIVILEGES ON *.* TO 'localroot'@'localhost';" | /usr/bin/mysql --user=root --password=passw0rd mysql

echo mysql -uroot -ppassw0rd pbxconf >  /usr/local/sbin/mydb
chmod +x /usr/local/sbin/mydb

# create pid dir
chown mysql:mysql -R /var/run/mariadb
echo "d /run/mariadb   710 mysql mysql" > /etc/tmpfiles.d/mariadb.conf

# save original MySQL config and replace it with customized

mv /etc/my.cnf /etc/my.cnf.orig

cat >> /etc/my.cnf <<-EOF
[mysqld]
datadir=/var/lib/mysql
pid-file=/run/mariadb/mariadb.pid
socket=/var/lib/mysql/mysql.sock
user=mysql
symbolic-links=0

sql_mode=NO_ENGINE_SUBSTITUTION

max_allowed_packet = 32M
max_connections = 200
# Query cache is often detrimental under concurrency; disable (removed in MariaDB 10.11+).
query_cache_type = 0
query_cache_size = 0
thread_cache_size = 32
tmp_table_size = 64M
max_heap_table_size = 64M
sort_buffer_size = 5M
read_rnd_buffer_size = 1M
table_open_cache = 1024
key_buffer_size = 32M
wait_timeout = 3600
interactive_timeout = 3600
myisam_max_sort_file_size = 4294967296

innodb_buffer_pool_size = 4G
innodb_file_per_table = 1

innodb_default_row_format = dynamic
innodb_strict_mode = OFF
innodb_page_size = 32k

[mysqld_safe]
log-error = /var/log/mysqld.log
pid-file = /run/mariadb/mariadb.pid

[client]
socket=/var/lib/mysql/mysql.sock
EOF

#sed -i 's|^\[mysqld\]|[mysqld]\n\nsql_mode=NO_ENGINE_SUBSTITUTION\n|' /etc/my.cnf

systemctl stop mariadb
rm -f /var/lib/mysql/ibdata* /var/lib/mysql/ib_logfile*
sed -i /lib/systemd/system/mariadb.service -e "s/^PrivateTmp=.*$/PrivateTmp=false/"
systemctl daemon-reload
systemctl start mariadb

