#!/bin/bash
# Production Debugging Script for 502 Bad Gateway
# Run this on your production server to diagnose issues

echo "==================================================================="
echo "🔍 STIFTUNG PRODUCTION DEBUGGING SCRIPT"
echo "==================================================================="
echo "Current time: $(date)"
echo

echo "📁 Current directory and .env file check:"
pwd
echo "--- .env file exists? ---"
ls -la .env 2>/dev/null && echo "✅ .env file found" || echo "❌ .env file missing"
echo

echo "🐳 Docker container status:"
docker-compose -f compose.yml ps
echo

echo "📊 Container resource usage:"
docker stats --no-stream
echo

echo "📋 Recent container logs (last 50 lines each):"
echo "--- WEB CONTAINER LOGS ---"
docker-compose -f compose.yml logs --tail=50 web
echo
echo "--- DATABASE CONTAINER LOGS ---"
docker-compose -f compose.yml logs --tail=50 db
echo
echo "--- REDIS CONTAINER LOGS ---"
docker-compose -f compose.yml logs --tail=50 redis
echo

echo "🌐 Network connectivity test:"
echo "--- Can we reach the web container internally? ---"
docker-compose -f compose.yml exec web curl -f http://localhost:8000/admin/ 2>/dev/null && echo "✅ Django responding internally" || echo "❌ Django not responding internally"
echo

echo "💾 Database connectivity test:"
echo "--- Database connection test ---"
docker-compose -f compose.yml exec web python manage.py check --database default 2>/dev/null && echo "✅ Database connected" || echo "❌ Database connection failed"
echo

echo "🔧 Django management commands:"
echo "--- Running Django check ---"
docker-compose -f compose.yml exec web python manage.py check
echo

echo "🚀 Environment variables (sensitive values hidden):"
docker-compose -f compose.yml exec web printenv | grep -E '^(DJANGO_|POSTGRES_|DB_|REDIS_)' | sed 's/=.*/=***HIDDEN***/'
echo

echo "==================================================================="
echo "🎯 DEBUGGING COMPLETE"
echo "==================================================================="