#!/bin/bash
set -e

echo "🚀 Deploying Rezepte Klaus with Traefik Proxy..."

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

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

# Validate required environment variables
if [ -z "$MYSQL_PASSWORD" ] || [ -z "$DOMAIN" ] || [ -z "$ACME_EMAIL" ]; then
    echo "❌ Error: Required environment variables not set in .env.production"
    echo "Please configure MYSQL_PASSWORD, DOMAIN, and ACME_EMAIL"
    exit 1
fi

# 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

# Check if required SQL files exist
REQUIRED_FILES=("Rezepte.sql" "ingredients.sql" "Zubereitung.sql" "rezepte_bilder.sql")
for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "$file" ]; then
        echo "❌ Error: Required SQL file $file not found!"
        echo "Please ensure all SQL files are present in the current directory."
        exit 1
    fi
done

# Create acme.json with correct permissions for Let's Encrypt
if [ ! -f ./acme.json ]; then
    echo "🔒 Creating acme.json for Let's Encrypt..."
    touch ./acme.json
    chmod 600 ./acme.json
fi

echo "🛑 Stopping existing containers..."
docker compose -f docker compose.traefik.yml down

echo "📥 Pulling latest images from registry..."
docker compose -f docker compose.traefik.yml pull backend frontend

echo "🚀 Starting containers with Traefik proxy..."
docker compose -f docker compose.traefik.yml up -d

echo "⏳ Waiting for services to start..."
sleep 45

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

if [ "$HEALTHY_SERVICES" -ge 6 ]; then
    echo "✅ Deployment successful!"
    echo ""
    echo "🌐 Your application is available at:"
    echo "   Main App: https://rezepte.$DOMAIN"
    echo "   phpMyAdmin: https://phpmyadmin.$DOMAIN"
    echo "   Portainer: https://portainer.$DOMAIN"
    echo "   Traefik Dashboard: https://traefik.$DOMAIN (admin/admin - please change!)"
    echo ""
    echo "📊 Service Status:"
    docker compose -f docker compose.traefik.yml ps
    echo ""
    echo "🏷️  Image Information:"
    echo "Backend:  ${BACKEND_IMAGE:-ghcr.io/your-username/rezepte-klaus-backend:latest}"
    echo "Frontend: ${FRONTEND_IMAGE:-ghcr.io/your-username/rezepte-klaus-frontend:latest}"
    echo ""
    echo "🔒 SSL Certificates:"
    echo "Traefik will automatically request Let's Encrypt certificates."
    echo "This may take a few minutes on first deployment."
else
    echo "❌ Deployment failed! Check logs:"
    docker compose -f docker compose.traefik.yml logs --tail=50
    exit 1
fi

echo ""
echo "📋 Useful commands:"
echo "  View logs: docker compose -f docker compose.traefik.yml logs -f"
echo "  Update: docker compose -f docker compose.traefik.yml pull && docker compose -f docker compose.traefik.yml up -d"
echo "  Stop: docker compose -f docker compose.traefik.yml down"
echo "  View Traefik logs: docker compose -f docker compose.traefik.yml logs traefik"