#!/bin/bash
set -e

echo "🗄️  Setting up Rezepte Klaus with external MySQL (Gitea)"
echo "======================================================"

# Check if .env.external-db exists
if [ ! -f .env.external-db ]; then
    echo "❌ Error: .env.external-db file not found!"
    echo "Please copy .env.external-db.example to .env.external-db and configure it."
    exit 1
fi

# Load environment variables
export $(cat .env.external-db | grep -v '^#' | xargs)

# Validate required environment variables
if [ -z "$MYSQL_HOST" ] || [ -z "$MYSQL_ADMIN_PASSWORD" ] || [ -z "$MYSQL_REZEPTE_PASSWORD" ]; then
    echo "❌ Error: Required MySQL environment variables not set in .env.external-db"
    echo "Please configure MYSQL_HOST, MYSQL_ADMIN_PASSWORD, and MYSQL_REZEPTE_PASSWORD"
    exit 1
fi

echo "🔍 Detecting Gitea MySQL setup..."

# Find Gitea MySQL container
MYSQL_CONTAINERS=$(docker ps --format "table {{.Names}}\t{{.Image}}" | grep mysql | head -5)
echo "Available MySQL containers:"
echo "$MYSQL_CONTAINERS"
echo ""

# Check if specified MySQL container exists and is running
if ! docker ps --format "{{.Names}}" | grep -q "^${MYSQL_HOST}$"; then
    echo "❌ Error: MySQL container '${MYSQL_HOST}' not found or not running!"
    echo "Available MySQL containers:"
    docker ps --format "table {{.Names}}\t{{.Image}}" | grep mysql
    echo ""
    echo "Please update MYSQL_HOST in .env.external-db"
    exit 1
fi

# Check if external network exists
if ! docker network ls --format "{{.Name}}" | grep -q "^${EXTERNAL_MYSQL_NETWORK}$"; then
    echo "❌ Error: Network '${EXTERNAL_MYSQL_NETWORK}' not found!"
    echo "Available networks:"
    docker network ls --format "table {{.Name}}\t{{.Driver}}"
    echo ""
    echo "Please update EXTERNAL_MYSQL_NETWORK in .env.external-db"
    exit 1
fi

echo "✅ MySQL container '${MYSQL_HOST}' found and running"
echo "✅ Network '${EXTERNAL_MYSQL_NETWORK}' exists"

# Test MySQL connection
echo "🔗 Testing MySQL connection..."
if docker exec -i "$MYSQL_HOST" mysql -u"${MYSQL_ADMIN_USER:-root}" -p"${MYSQL_ADMIN_PASSWORD}" -e "SELECT VERSION();" > /dev/null 2>&1; then
    echo "✅ MySQL connection successful"
else
    echo "❌ Error: Cannot connect to MySQL!"
    echo "Please check MYSQL_ADMIN_PASSWORD in .env.external-db"
    exit 1
fi

# Create database and user
echo "🏗️  Setting up Rezepte Klaus database..."

# SQL commands for database setup
DATABASE_SETUP_SQL="
-- Create Rezepte Klaus database
CREATE DATABASE IF NOT EXISTS rezepte_klaus 
CHARACTER SET utf8mb4 
COLLATE utf8mb4_unicode_ci;

-- Create dedicated user for Rezepte Klaus
CREATE USER IF NOT EXISTS 'rezepte_user'@'%' IDENTIFIED BY '${MYSQL_REZEPTE_PASSWORD}';

-- Grant permissions
GRANT ALL PRIVILEGES ON rezepte_klaus.* TO 'rezepte_user'@'%';

-- Refresh privileges
FLUSH PRIVILEGES;

-- Show created database
SHOW DATABASES LIKE 'rezepte_klaus';
"

# Execute database setup
echo "$DATABASE_SETUP_SQL" | docker exec -i "$MYSQL_HOST" mysql -u"${MYSQL_ADMIN_USER:-root}" -p"${MYSQL_ADMIN_PASSWORD}"

if [ $? -eq 0 ]; then
    echo "✅ Database 'rezepte_klaus' and user 'rezepte_user' created successfully"
else
    echo "❌ Error creating database or user"
    exit 1
fi

# Import SQL files if they exist
echo "📊 Importing initial data..."
REQUIRED_FILES=("Rezepte.sql" "ingredients.sql" "Zubereitung.sql" "rezepte_bilder.sql")

for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "$file" ]; then
        echo "  Importing $file..."
        docker exec -i "$MYSQL_HOST" mysql -u"${MYSQL_ADMIN_USER:-root}" -p"${MYSQL_ADMIN_PASSWORD}" rezepte_klaus < "$file"
        if [ $? -eq 0 ]; then
            echo "  ✅ $file imported successfully"
        else
            echo "  ⚠️  Warning: Failed to import $file"
        fi
    else
        echo "  ⚠️  Warning: $file not found, skipping..."
    fi
done

# Login to CitySensor registry if credentials are provided
if [ -n "$DOCKER_USERNAME" ] && [ -n "$DOCKER_PASSWORD" ] && [ -n "$DOCKER_REGISTRY" ]; then
    echo "🔐 Logging into CitySensor registry..."
    echo "$DOCKER_PASSWORD" | docker login "$DOCKER_REGISTRY" -u "$DOCKER_USERNAME" --password-stdin
fi

# Pull latest images
echo "📥 Pulling latest images..."
docker-compose -f docker-compose.traefik-external-db.yml pull

# Start services
echo "🚀 Starting Rezepte Klaus services with external MySQL..."
docker-compose -f docker-compose.traefik-external-db.yml up -d

# Wait for services to be healthy
echo "⏳ Waiting for services to start..."
sleep 45

echo "🔍 Checking service health..."
HEALTHY_SERVICES=$(docker-compose -f docker-compose.traefik-external-db.yml ps --filter "status=running" --format "table {{.Service}}\t{{.Status}}" | grep -c "Up" || true)

if [ "$HEALTHY_SERVICES" -ge 4 ]; then
    echo "✅ Deployment successful!"
    echo ""
    echo "🌐 Your application is available at:"
    echo "   Main App: https://rezepte.$DOMAIN"
    echo "   phpMyAdmin: https://phpmyadmin.$DOMAIN (shows Gitea + Rezepte DBs)"
    echo "   Portainer: https://portainer.$DOMAIN"
    echo "   Traefik Dashboard: https://traefik.$DOMAIN (admin/admin - please change!)"
    echo ""
    echo "🗄️  Database Information:"
    echo "   MySQL Host: $MYSQL_HOST (shared with Gitea)"
    echo "   Rezepte Database: rezepte_klaus"
    echo "   Rezepte User: rezepte_user"
    echo ""
    echo "📊 Service Status:"
    docker-compose -f docker-compose.traefik-external-db.yml ps
    echo ""
    echo "💡 phpMyAdmin now shows both Gitea and Rezepte Klaus databases!"
else
    echo "❌ Deployment failed! Check logs:"
    docker-compose -f docker-compose.traefik-external-db.yml logs --tail=50
    exit 1
fi

echo ""
echo "📋 Useful commands:"
echo "  View logs: docker-compose -f docker-compose.traefik-external-db.yml logs -f"
echo "  Update: docker-compose -f docker-compose.traefik-external-db.yml pull && docker-compose -f docker-compose.traefik-external-db.yml up -d"
echo "  Stop: docker-compose -f docker-compose.traefik-external-db.yml down"
echo "  Database access: docker exec -it $MYSQL_HOST mysql -urezepte_user -p rezepte_klaus"