#!/bin/bash # Configuration CONTAINER_NAME="ckb-mysql-dev" DB_NAME="ckb_db" DB_USER="root" DB_PASSWORD="root" BACKUP_DIR="./backups" # Function to show available backups show_backups() { echo "📁 Available backup files:" echo "----------------------------------------" ls -la "$BACKUP_DIR"/*.sql* 2>/dev/null | awk '{print NR ". " $9 " (" $5 " bytes, " $6 " " $7 " " $8 ")"}' } # Function to restore database restore_database() { local backup_file="$1" echo "🔄 Starting database restore..." echo "Container: $CONTAINER_NAME" echo "Database: $DB_NAME" echo "Backup file: $backup_file" # Check if file exists if [[ ! -f "$backup_file" ]]; then echo "❌ Error: Backup file not found: $backup_file" exit 1 fi # Check if container is running if ! docker ps | grep -q $CONTAINER_NAME; then echo "❌ Error: Container $CONTAINER_NAME is not running!" exit 1 fi # Ask for confirmation read -p "⚠️ This will overwrite the current database. Continue? (y/n): " -n 1 -r echo if [[ ! $REPLY =~ ^[Yy]$ ]]; then echo "🚫 Restore cancelled." exit 0 fi # Check if file is compressed if [[ "$backup_file" == *.gz ]]; then echo "📦 Decompressing backup file..." if gunzip -c "$backup_file" | docker exec -i $CONTAINER_NAME mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME; then echo "✅ Database restored successfully from compressed backup!" else echo "❌ Restore failed!" exit 1 fi else echo "📥 Restoring from uncompressed backup..." if docker exec -i $CONTAINER_NAME mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME < "$backup_file"; then echo "✅ Database restored successfully!" else echo "❌ Restore failed!" exit 1 fi fi } # Main script echo "🗃️ CKB Database Restore Tool" echo "============================" # Check if backup directory exists if [[ ! -d "$BACKUP_DIR" ]]; then echo "❌ Error: Backup directory not found: $BACKUP_DIR" exit 1 fi # Show available backups show_backups # Check if any backup files exist if ! ls "$BACKUP_DIR"/*.sql* 1> /dev/null 2>&1; then echo "❌ No backup files found in $BACKUP_DIR" exit 1 fi echo echo "Options:" echo "1. Select backup file by number" echo "2. Enter custom backup file path" echo "3. Exit" echo read -p "Choose option (1-3): " -n 1 -r option echo case $option in 1) echo "📋 Available backups:" backup_files=($(ls "$BACKUP_DIR"/*.sql* 2>/dev/null)) for i in "${!backup_files[@]}"; do echo "$((i+1)). $(basename "${backup_files[$i]}")" done read -p "Enter backup number: " backup_number if [[ "$backup_number" =~ ^[0-9]+$ ]] && [[ "$backup_number" -ge 1 ]] && [[ "$backup_number" -le "${#backup_files[@]}" ]]; then selected_backup="${backup_files[$((backup_number-1))]}" restore_database "$selected_backup" else echo "❌ Invalid backup number!" exit 1 fi ;; 2) read -p "Enter backup file path: " custom_backup restore_database "$custom_backup" ;; 3) echo "👋 Goodbye!" exit 0 ;; *) echo "❌ Invalid option!" exit 1 ;; esac echo "🎉 Restore process completed!"