#!/bin/bash
# ==============================================
# ♻️ restore-db.sh — Restore MariaDB from backup
# ==============================================

set -e

echo "♻️ Restoring database from backup..."

# List available backups
echo "Available backups:"
ls -1 backups/*.sql 2>/dev/null || { echo "❌ No backups found."; exit 1; }

read -p "📂 Enter backup filename (from ./backups): " FILE

if [ ! -f "backups/$FILE" ]; then
    echo "❌ Backup file not found: backups/$FILE"
    exit 1
fi

# Load credentials
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)

echo "⚙️ Restoring to database: $MYSQL_DATABASE"
cat "backups/$FILE" | docker exec -i mariadb mysql -u$MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE

echo "✅ Database restored successfully from $FILE"
