#!/bin/bash -e
# Generated by CHEF
# Local modification will be overriden


<% mysql_cmd = mysqlbin_cmd(node['mariadb']['install']['prefer_scl_package'],
                            node['mariadb']['install']['version'],
                            'mysql')
   mysqladmin_cmd = mysqlbin_cmd(node['mariadb']['install']['prefer_scl_package'],
                                 node['mariadb']['install']['version'],
                                 'mysqladmin') %>
<% if node['mariadb']['allow_root_pass_change'] -%>
<% if node['mariadb']['server_root_password'].empty? -%>
<%= mysqladmin_cmd %> -u root password "$1"
<% else -%>
<%= mysqladmin_cmd %> -u root -p'<%= node['mariadb']['server_root_password'] %>' password "$1"
<% end -%>

<% end -%>
password_flag=""
if [ "$1" ]; then
  password_flag="-p$1"
fi

<% if node['mariadb']['remove_anonymous_users'] -%>
/bin/echo "DELETE FROM mysql.user WHERE User='';" | <%= mysql_cmd %> -u root ${password_flag}
<% end -%>

<% if node['mariadb']['forbid_remote_root'] -%>
user_exist=$(<%= mysql_cmd %> -u root ${password_flag} -D mysql -r -B -N -e "SELECT user from user where user = 'root' and host = '%'")
if [ "$user_exist" == "root" ]; then
  /bin/echo "DROP USER 'root'@'%';" | <%= mysql_cmd %> -u root ${password_flag}
fi
<% else -%>
/bin/echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '<%= node['mariadb']['server_root_password'] %>' WITH GRANT OPTION;" | <%= mysql_cmd %> -u root ${password_flag}
<% end -%>

<% if node['mariadb']['remove_test_database'] -%>
/bin/echo "DROP DATABASE IF EXISTS test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';" | <%= mysql_cmd %> -u root ${password_flag}
<% end -%>

/bin/echo "FLUSH PRIVILEGES;" | <%= mysql_cmd %> -u root ${password_flag}
