#!/bin/sh

# This script performs similar security routines that can be found
# in the mysql_secure_installation script that comes with MariaDB.

MYSQL="/usr/clearos/sandbox/usr/bin/mysql"
DB_CONFIG="/var/clearos/system_database/root"
ROOTPASS=`grep ^password $DB_CONFIG 2>/dev/null | sed "s/^password[[:space:]]*=[[:space:]]*//"`

if [ -z "$ROOTPASS" ]; then
    echo "Unable to authenticate with database"
    exit 1;
fi

# Remove anonymous users
#-----------------------

CHECK=`$MYSQL -uroot -p"$ROOTPASS" -e "SELECT * FROM mysql.user WHERE User='';" mysql`

if [ -n "$CHECK" ]; then
    logger -p local6.notice -t installer "app-system-database-core - removing anonymous users"
    $MYSQL -uroot -p"$ROOTPASS" -e "DELETE FROM mysql.user WHERE User='';" mysql
fi

# Remove remote root login
#--------------------------

CHECK=`$MYSQL -uroot -p"$ROOTPASS" -e "SELECT * FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');" mysql`

if [ -n "$CHECK" ]; then
    logger -p local6.notice -t installer "app-system-database-core - removing remote root login"
    $MYSQL -uroot -p"$ROOTPASS" -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');" mysql
fi


# Remove test database
#---------------------

CHECK=`$MYSQL -uroot -p"$ROOTPASS" -e "SHOW TABLES" test 2>/dev/null` 
if [ $? -eq 0 ]; then
    logger -p local6.notice -t installer "app-system-database-core - removing test database"
    $MYSQL -uroot -p"$ROOTPASS" -e "DROP DATABASE test;" mysql
    $MYSQL -uroot -p"$ROOTPASS" -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'" mysql
fi

# Reload privileges
#------------------

$MYSQL -uroot -p"$ROOTPASS" -e "FLUSH PRIVILEGES;" mysql
