#!/bin/bash
# ==============================================
# 💾 backup-db.sh — Backup MariaDB database
# ==============================================

set -e

echo "💾 Creating database backup..."

# Ensure backup directory exists
mkdir -p backups

# Load credentials from .env
MYSQL_USER=$(grep MYSQL_USER .env | cut -d= -f2)
MYSQL_PASSWORD=$(grep MYSQL_PASSWORD .env | cut -d= -f2)
MYSQL_DATABASE=$(grep MYSQL_DATABASE .env | cut -d= -f2)

# Check for required values
if [ -z "$MYSQL_USER" ] || [ -z "$MYSQL_PASSWORD" ] || [ -z "$MYSQL_DATABASE" ]; then
    echo "❌ Missing MySQL credentials in .env (MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE)."
    exit 1
fi

# Generate filename with timestamp
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="backups/backup_${MYSQL_DATABASE}_${TIMESTAMP}.sql"

# Run dump inside the mariadb container
docker exec mariadb sh -c "mysqldump -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE" > "$BACKUP_FILE"

if [ $? -eq 0 ]; then
    echo "✅ Backup created successfully: $BACKUP_FILE"
else
    echo "❌ Backup failed."
    exit 1
fi
