#!/bin/sh

# Start the system database if not already running
#-------------------------------------------------

if [ ! -e /var/lib/system-mysql/mysql.sock ]; then
    if [ -e /usr/lib/systemd/system/system-mariadb.service ]; then
        systemctl enable system-mariadb.service
        systemctl start system-mariadb.service
    else
        exit 1
    fi

    sleep 3
fi

# Create default password if one is not set
#------------------------------------------

/usr/clearos/sandbox/usr/bin/mysqladmin -uroot -hlocalhost status >/dev/null 2>&1
dbret=$?

if [ $dbret -eq 0 ]; then
    logger -p local6.notice -t installer "app-system-database-core - initializing password"

    umask 0177
    PASSWORD=`openssl rand -base64 30`
    echo "password = $PASSWORD" > /var/clearos/system_database/root
    /usr/clearos/sandbox/usr/bin/mysqladmin -uroot -hlocalhost password $PASSWORD >/dev/null 2>&1
    /usr/clearos/sandbox/usr/bin/mysqladmin -uroot -p$PASSWORD -hlocalhost flush-privileges >/dev/null 2>&1

    # Drop test database if it exists (cruft)
    /usr/clearos/sandbox/usr/bin/mysqladmin -uroot -p$PASSWORD -hlocalhost -f drop test >/dev/null 2>&1
fi

chmod 640 /var/clearos/system_database/root
chown root.system-mysql /var/clearos/system_database/root
