diff --git a/apps/database/healthcheck.sh b/apps/database/healthcheck.sh new file mode 100755 index 0000000..b46c856 --- /dev/null +++ b/apps/database/healthcheck.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +# Credentials from environment variables +MYSQL_USER="${MARIADB_USER:-default}" +MYSQL_PASSWORD="${MARIADB_PASSWORD:-default}" +MYSQL_HOST="127.0.0.1" + +ROOT_PASSWORD=$(cat /run/secrets/mariadb_root) + +echo "🔑 READ ROOT PASSWORD FROM SECRETS" + +# Check if MariaDB is running +if ! mariadb -h "$MYSQL_HOST" -u root -p"$ROOT_PASSWORD" -e "SELECT 1;" &>/dev/null; then + echo "❌ MariaDB is not responding" + exit 1 +fi + +# Check if a specific user exists +USER_EXISTS=$(mariadb -h "$MYSQL_HOST" -u root -p"$ROOT_PASSWORD" -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '${MYSQL_USER}');" | tail -n 1) + +if [ "$USER_EXISTS" -ne 1 ]; then + echo "❌ User '${MYSQL_USER}' does not exist" + exit 1 +fi + +# Check if the user can log in with the provided password +if ! mariadb -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SELECT 1;" &>/dev/null; then + echo "❌ User '${MYSQL_USER}' exists, but authentication failed with the provided password." + exit 1 +fi + +echo "✅ MariaDB is healthy" +exit 0 diff --git a/apps/database/init-user.sh b/apps/database/init-user.sh new file mode 100644 index 0000000..14777b1 --- /dev/null +++ b/apps/database/init-user.sh @@ -0,0 +1,74 @@ +#!/bin/bash +echo "🔄 Running MariaDB initialization script..." + +# Wait until MariaDB is ready +until mysqladmin ping -h localhost --silent; do + sleep 2 +done + +echo "✅ MariaDB is ready. Checking root credentials..." + +# Try logging in with the root password +if ! mysql -u root -p"$MARIADB_ROOT_PASSWORD" -e "SELECT 1;" &>/dev/null; then + echo "❌ ERROR: Root password in .env does not match the database!" + echo "🔄 Attempting to reset the root password..." + + # Stop MariaDB safely + echo "⚠️ Stopping MariaDB..." + service mysql stop || pkill mysqld + sleep 5 + + # Start MariaDB in recovery mode + echo "🚀 Starting MariaDB in recovery mode..." + mysqld_safe --skip-grant-tables --skip-networking & + sleep 5 + + # Reset root password + echo "🔐 Resetting root password..." + mysql -u root < /dev/null; echo "$?") + +if [ "$DB_EXISTS" -ne 0 ]; then + echo "⚠️ Database '${MARIADB_DATABASE}' does not exist. Creating it now..." + mysql -u root -p"$MARIADB_ROOT_PASSWORD" -e "CREATE DATABASE ${MARIADB_DATABASE};" + echo "✅ Database '${MARIADB_DATABASE}' created!" +else + echo "✅ Database '${MARIADB_DATABASE}' already exists." +fi + +# Ensure the database user exists and has the correct password +USER_EXISTS=$(mysql -u root -p"$MARIADB_ROOT_PASSWORD" -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '${MARIADB_USER}');" | tail -n 1) + +if [ "$USER_EXISTS" -eq 0 ]; then + echo "⚠️ User '${MARIADB_USER}' does not exist. Creating it now..." + mysql -u root -p"$MARIADB_ROOT_PASSWORD" <