#!/bin/bash

# Simpler alternative: Start MySQL and use mysqldump
# This assumes the data directory is compatible with MySQL 8.0

set -e

BACKUP_DIR="./nitescape_mysql_data/_data"
OUTPUT_FILE="${1:-./nitescape_backup.sql}"
CONTAINER_NAME="nitescape-mysql-export-$(date +%s)"
TEMP_DATA_DIR="/tmp/nitescape-mysql-temp-$(date +%s)"
MYSQL_ROOT_PASSWORD="export_temp_$(openssl rand -hex 8)"

# Cleanup function
cleanup() {
    echo "Cleaning up..."
    docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
    # Try normal removal first, then sudo if needed (for files changed by MySQL)
    rm -rf "$TEMP_DATA_DIR" 2>/dev/null || sudo rm -rf "$TEMP_DATA_DIR" 2>/dev/null || true
}
trap cleanup EXIT

echo "Copying backup data to temporary location..."
echo "This may take a minute or two..."
mkdir -p "$TEMP_DATA_DIR"
cp -r "$BACKUP_DIR"/* "$TEMP_DATA_DIR"/

echo "Starting MySQL container with your backup data..."
echo "Note: Using --skip-grant-tables to bypass authentication (safe for read-only export)"

# Start MySQL container with skip-grant-tables to bypass password authentication
# This allows us to connect without knowing the original root password
docker run -d \
    --name "$CONTAINER_NAME" \
    -v "$TEMP_DATA_DIR:/var/lib/mysql" \
    mysql:8.0 \
    --skip-grant-tables

echo "Waiting for MySQL to start..."
sleep 20

# Try to connect and export (without password since we're using skip-grant-tables)
for i in {1..30}; do
    # Check if MySQL is ready by trying to connect
    if docker exec "$CONTAINER_NAME" mysql -uroot -e "SELECT 1" >/dev/null 2>&1; then
        echo "MySQL is ready! Exporting..."
        docker exec "$CONTAINER_NAME" mysqldump \
            -uroot \
            --all-databases \
            --routines \
            --triggers \
            --events \
            --skip-lock-tables > "$OUTPUT_FILE"
        
        if [ -s "$OUTPUT_FILE" ]; then
            echo "✓ Success! Exported to: $OUTPUT_FILE"
            echo "File size: $(du -h "$OUTPUT_FILE" | cut -f1)"
            docker rm -f "$CONTAINER_NAME"
            rm -rf "$TEMP_DATA_DIR"
            exit 0
        else
            echo "Warning: Export file is empty. Check container logs:"
            docker logs "$CONTAINER_NAME"
            exit 1
        fi
    fi
    sleep 2
done

echo "Error: MySQL did not start in time. Container logs:"
docker logs "$CONTAINER_NAME"
exit 1

