#!/bin/bash

# Database restore script for Docker MySQL container
# Usage: ./restore-database.sh <backup_file.sql.gz>

# Configuration
CONTAINER_NAME="aufg_mysql"
DATABASE_NAME="aufg_laravel"
USERNAME="laravel"
PASSWORD="laravel123"
BACKUP_DIR="./docker/mysql/backup"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if backup file is provided
if [ $# -eq 0 ]; then
    echo -e "${RED}Error: Please provide a backup file!${NC}"
    echo "Usage: $0 <backup_file.sql.gz>"
    echo ""
    echo "Available backups:"
    ls -la "$BACKUP_DIR"/*.sql.gz 2>/dev/null || echo "No backup files found in $BACKUP_DIR"
    exit 1
fi

BACKUP_FILE="$1"

# Check if backup file exists
if [[ ! "$BACKUP_FILE" = /* ]]; then
    # If not absolute path, check in backup directory
    BACKUP_FILE="$BACKUP_DIR/$BACKUP_FILE"
fi

if [ ! -f "$BACKUP_FILE" ]; then
    echo -e "${RED}Error: Backup file '$BACKUP_FILE' not found!${NC}"
    exit 1
fi

echo -e "${YELLOW}Starting database restore...${NC}"

# Check if Docker container is running
if ! docker ps | grep -q "$CONTAINER_NAME"; then
    echo -e "${RED}Error: MySQL container '$CONTAINER_NAME' is not running!${NC}"
    echo "Please start the container with: docker-compose up -d mysql"
    exit 1
fi

# Confirm restoration
echo -e "${YELLOW}WARNING: This will replace the existing database '$DATABASE_NAME'!${NC}"
read -p "Are you sure you want to continue? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Restore cancelled.${NC}"
    exit 0
fi

# Copy backup file to container
echo -e "${YELLOW}Copying backup file to container...${NC}"
docker cp "$BACKUP_FILE" "$CONTAINER_NAME:/tmp/restore_backup.sql.gz"

if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Failed to copy backup file to container!${NC}"
    exit 1
fi

# Drop and recreate database
echo -e "${YELLOW}Recreating database...${NC}"
docker exec "$CONTAINER_NAME" mysql -u"$USERNAME" -p"$PASSWORD" -e "DROP DATABASE IF EXISTS $DATABASE_NAME; CREATE DATABASE $DATABASE_NAME;"

if [ $? -ne 0 ]; then
    echo -e "${RED}✗ Failed to recreate database!${NC}"
    exit 1
fi

# Restore database from backup
echo -e "${YELLOW}Restoring database from backup...${NC}"
docker exec "$CONTAINER_NAME" bash -c "gunzip -c /tmp/restore_backup.sql.gz | mysql -u$USERNAME -p$PASSWORD"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Database restored successfully!${NC}"
    echo -e "${GREEN}✓ Database '$DATABASE_NAME' has been restored from: $BACKUP_FILE${NC}"
    
    # Clean up temporary file
    docker exec "$CONTAINER_NAME" rm -f /tmp/restore_backup.sql.gz
    
else
    echo -e "${RED}✗ Database restore failed!${NC}"
    exit 1
fi

echo -e "${GREEN}Database restore completed!${NC}"
echo ""
echo "You may need to:"
echo "  1. Clear Laravel cache: php artisan cache:clear"
echo "  2. Migrate if needed: php artisan migrate"
echo "  3. Restart your application server"