#!/bin/bash
set -e

echo "🚀 Starting Docker build with network resilience..."

# Prüfe Netzwerk-Konnektivität
echo "🔍 Checking network connectivity..."
if ! curl -s --connect-timeout 5 https://registry-1.docker.io/v2/ > /dev/null; then
    echo "⚠️  Docker Hub nicht erreichbar - verwende lokale Images"
    export DOCKER_BUILDKIT=0
    export COMPOSE_DOCKER_CLI_BUILD=0
fi

# DNS-Cache leeren
echo "🔄 Flushing DNS cache..."
sudo systemctl flush-dns 2>/dev/null || sudo systemd-resolve --flush-caches 2>/dev/null || true

# Docker daemon neu starten falls nötig
if ! docker info > /dev/null 2>&1; then
    echo "🔄 Restarting Docker daemon..."
    sudo systemctl restart docker
    sleep 5
fi

# Versuche erst mit Pull
echo "📥 Attempting to pull base images..."
if timeout 60 docker-compose pull --ignore-pull-failures; then
    echo "✅ Images pulled successfully"
else
    echo "⚠️  Pull failed - building with local images only"
fi

# Build mit verschiedenen Strategien
echo "🏗️  Building containers..."

# Strategie 1: Normaler Build
if timeout 300 docker-compose build --parallel; then
    echo "✅ Build completed successfully!"
    exit 0
fi

echo "⚠️  Normal build failed - trying fallback strategies..."

# Strategie 2: Ohne Cache und Pull
if timeout 300 docker-compose build --no-cache --pull=false; then
    echo "✅ Build completed with fallback strategy!"
    exit 0
fi

# Strategie 3: Sequenzieller Build
echo "🔄 Trying sequential build..."
for service in web php db redis queue-worker; do
    echo "Building $service..."
    if timeout 300 docker-compose build --no-cache --pull=false "$service"; then
        echo "✅ $service built successfully"
    else
        echo "❌ Failed to build $service"
    fi
done

echo "🏁 Build process completed"
