#!/bin/bash

# Script to export MySQL Docker backup data directory to SQL file
# Usage: ./scripts/export-mysql-backup.sh [output-file.sql]

set -e

# Configuration
BACKUP_DIR="./nitescape_mysql_data/_data"
OUTPUT_FILE="${1:-./nitescape_backup.sql}"
CONTAINER_NAME="nitescape-mysql-export-temp"
MYSQL_VERSION="8.0"
MYSQL_ROOT_PASSWORD="temp_root_password_$(date +%s)"

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

echo -e "${GREEN}MySQL Backup Export Script${NC}"
echo "================================"

# Check if backup directory exists
if [ ! -d "$BACKUP_DIR" ]; then
    echo -e "${RED}Error: Backup directory not found at $BACKUP_DIR${NC}"
    exit 1
fi

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    echo -e "${RED}Error: Docker is not running. Please start Docker first.${NC}"
    exit 1
fi

# Clean up any existing container
echo -e "${YELLOW}Cleaning up any existing containers...${NC}"
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true

# Start MySQL container with the backup data directory
echo -e "${YELLOW}Starting temporary MySQL container...${NC}"
docker run -d \
    --name "$CONTAINER_NAME" \
    -e MYSQL_ROOT_PASSWORD="$MYSQL_ROOT_PASSWORD" \
    -v "$(pwd)/$BACKUP_DIR:/var/lib/mysql" \
    mysql:$MYSQL_VERSION \
    --datadir=/var/lib/mysql \
    --skip-grant-tables \
    --skip-networking

# Wait for MySQL to be ready
echo -e "${YELLOW}Waiting for MySQL to start...${NC}"
sleep 10

# Check if container is running
if ! docker ps | grep -q "$CONTAINER_NAME"; then
    echo -e "${RED}Error: Container failed to start. Checking logs...${NC}"
    docker logs "$CONTAINER_NAME"
    exit 1
fi

# Alternative approach: Use mysqldump from within the container
# First, we need to start MySQL normally (not with skip-grant-tables)
echo -e "${YELLOW}Restarting container with normal MySQL configuration...${NC}"
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true

# Start MySQL container normally
docker run -d \
    --name "$CONTAINER_NAME" \
    -e MYSQL_ROOT_PASSWORD="$MYSQL_ROOT_PASSWORD" \
    -v "$(pwd)/$BACKUP_DIR:/var/lib/mysql" \
    mysql:$MYSQL_VERSION

# Wait for MySQL to be ready
echo -e "${YELLOW}Waiting for MySQL to initialize...${NC}"
for i in {1..30}; do
    if docker exec "$CONTAINER_NAME" mysqladmin ping -h localhost --silent 2>/dev/null; then
        echo -e "${GREEN}MySQL is ready!${NC}"
        break
    fi
    if [ $i -eq 30 ]; then
        echo -e "${RED}Error: MySQL failed to start within 60 seconds${NC}"
        docker logs "$CONTAINER_NAME"
        docker rm -f "$CONTAINER_NAME"
        exit 1
    fi
    sleep 2
done

# Export the database
echo -e "${YELLOW}Exporting database to $OUTPUT_FILE...${NC}"
docker exec "$CONTAINER_NAME" mysqldump \
    -uroot \
    -p"$MYSQL_ROOT_PASSWORD" \
    --all-databases \
    --routines \
    --triggers \
    --events \
    --single-transaction \
    --quick \
    --lock-tables=false > "$OUTPUT_FILE"

# Check if export was successful
if [ $? -eq 0 ] && [ -s "$OUTPUT_FILE" ]; then
    echo -e "${GREEN}✓ Successfully exported database to $OUTPUT_FILE${NC}"
    echo -e "${GREEN}File size: $(du -h "$OUTPUT_FILE" | cut -f1)${NC}"
else
    echo -e "${RED}Error: Export failed or file is empty${NC}"
    docker rm -f "$CONTAINER_NAME"
    exit 1
fi

# Clean up
echo -e "${YELLOW}Cleaning up temporary container...${NC}"
docker rm -f "$CONTAINER_NAME"

echo -e "${GREEN}✓ Done! Your SQL backup is ready at: $OUTPUT_FILE${NC}"
echo -e "${YELLOW}You can now import it using: mysql -u root -p < $OUTPUT_FILE${NC}"

