#!/bin/bash

DEFAULT_MDB_DATADIR=/var/lib/mysql/
INSTALL_PREFIX=/usr

# 1. Check if MariaDB is running
echo "Checking MariaDB status..."
if mariadb-admin ping &>/dev/null; then
    # Get and show current PID
    MDB_PID=$(pgrep -x mariadbd || pgrep -x mysqld)
    echo "MariaDB is RUNNING (PID: $MDB_PID)."
    
    # 2. Shutdown MariaDB
    echo "Stopping MariaDB..."
    mariadb -e "shutdown;"
    
    # Wait for the process to completely terminate
    while pgrep -x mariadbd >/dev/null || pgrep -x mysqld >/dev/null; do 
        sleep 1
    done
    echo "MariaDB stopped."
else
    echo "MariaDB is NOT running."
fi

# 3. Start MariaDB
echo "Starting MariaDB..."
"$INSTALL_PREFIX/bin/mariadbd-safe" --datadir="$DEFAULT_MDB_DATADIR" &

# Wait for MariaDB to become responsive
echo "Waiting for MariaDB to accept connections..."
until mariadb-admin ping &>/dev/null; do
    sleep 1
done

# 4. Show the new PID
NEW_PID=$(pgrep -x mariadbd || pgrep -x mysqld)
mariadb -e "SELECT 1" >/dev/null
echo "MariaDB started successfully (New PID: $NEW_PID)."

