|
| 1 | +#!/usr/bin/env bash |
| 2 | +# MariaDB/MySQL initialization script for Cypht |
| 3 | +# This script runs in /docker-entrypoint-initdb.d/ and ensures the database user |
| 4 | +# has proper permissions for Docker networking. |
| 5 | +# |
| 6 | +# It is intended to be used **only** with MariaDB/MySQL. |
| 7 | +# - It creates the application user with '@%' host for Docker network connections |
| 8 | +# - It also ensures a '@localhost' user exists for local access / healthchecks |
| 9 | +# |
| 10 | +# Note: SQLite and PostgreSQL do not use this script: |
| 11 | +# - SQLite is file-based, has no users, and is accessed directly by the app |
| 12 | +# - PostgreSQL should be configured using its own mechanisms; this script does not touch it |
| 13 | + |
| 14 | +set -e |
| 15 | + |
| 16 | +# MySQL/MariaDB initialization |
| 17 | +MYSQL_USER="${MYSQL_USER:-cypht}" |
| 18 | +MYSQL_PASSWORD="${MYSQL_PASSWORD:-cypht_password}" |
| 19 | +MYSQL_DATABASE="${MYSQL_DATABASE:-cypht}" |
| 20 | + |
| 21 | +# Get root password - MariaDB init scripts can access this via environment or file |
| 22 | +if [ -n "$MYSQL_ROOT_PASSWORD_FILE" ] && [ -f "$MYSQL_ROOT_PASSWORD_FILE" ]; then |
| 23 | + MYSQL_ROOT_PASSWORD=$(cat "$MYSQL_ROOT_PASSWORD_FILE") |
| 24 | +elif [ -n "$MYSQL_ROOT_PASSWORD" ]; then |
| 25 | + MYSQL_ROOT_PASSWORD="$MYSQL_ROOT_PASSWORD" |
| 26 | +else |
| 27 | + echo "Error: MYSQL_ROOT_PASSWORD not set" >&2 |
| 28 | + exit 1 |
| 29 | +fi |
| 30 | + |
| 31 | +# Create user with wildcard host (%) to allow connections from any Docker container |
| 32 | +# This is necessary because Docker containers connect via service names, not localhost. |
| 33 | +# Note: MYSQL_USER environment variable creates 'user'@'localhost', but we also need 'user'@'%'. |
| 34 | +mysql -u root -p"${MYSQL_ROOT_PASSWORD}" <<EOF_SQL |
| 35 | +-- Create user with wildcard host for Docker network connections |
| 36 | +-- This allows connections from any container in the Docker network |
| 37 | +CREATE USER IF NOT EXISTS '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}'; |
| 38 | +GRANT ALL PRIVILEGES ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'%'; |
| 39 | +
|
| 40 | +-- Ensure localhost user exists (may already exist from MYSQL_USER env var) |
| 41 | +CREATE USER IF NOT EXISTS '${MYSQL_USER}'@'localhost' IDENTIFIED BY '${MYSQL_PASSWORD}'; |
| 42 | +GRANT ALL PRIVILEGES ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'localhost'; |
| 43 | +
|
| 44 | +-- Flush privileges to ensure changes take effect |
| 45 | +FLUSH PRIVILEGES; |
| 46 | +EOF_SQL |
| 47 | + |
| 48 | +echo "✓ Created MySQL/MariaDB user '${MYSQL_USER}' with Docker network permissions (@'%' and @'localhost')" |
| 49 | + |
0 commit comments