#!/bin/bash
# BTCPay Server Bad Gateway Fix Script
# Run this on the server as root

echo "=== BTCPay Server Bad Gateway Troubleshooting ==="
echo "Date: $(date)"
echo ""

# 1. Check disk space
echo "1. Checking disk space..."
df -h / | grep -v Filesystem
echo ""

# 2. Check memory
echo "2. Checking memory..."
free -h | grep Mem
echo ""

# 3. Check Docker service
echo "3. Checking Docker service..."
systemctl status docker | head -5
echo ""

# 4. List all containers (running and stopped)
echo "4. Checking container status..."
docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.State}}" | head -15
echo ""

# 5. Check BTCPay container specifically
echo "5. BTCPay Server container logs (last 20 lines)..."
docker logs generated_btcpayserver_1 2>&1 | tail -20
echo ""

# 6. Check nginx container
echo "6. Nginx container logs (last 10 lines)..."
docker logs generated_nginx_1 2>&1 | tail -10
echo ""

# 7. Check PostgreSQL
echo "7. PostgreSQL container status..."
docker logs generated_postgres_1 2>&1 | tail -5
echo ""

# Quick fix attempts
echo "=== Attempting Quick Fixes ==="

# 8. Restart BTCPay container
echo "8. Restarting BTCPay Server container..."
docker restart generated_btcpayserver_1
sleep 5

# 9. Check if it's running now
echo "9. BTCPay container status after restart:"
docker ps | grep btcpayserver
echo ""

# 10. If still not working, restart all BTCPay services
echo "10. If still having issues, restart all services with:"
echo "   cd /opt/btcpayserver-docker && ./btcpay-restart.sh"
echo ""

# 11. Nuclear option - restart Docker
echo "11. If nothing works, restart Docker daemon:"
echo "   systemctl restart docker"
echo "   cd /opt/btcpayserver-docker && ./btcpay-restart.sh"
echo ""

echo "=== Diagnostic Summary ==="
docker ps --format "table {{.Names}}\t{{.Status}}" | grep -E "btcpay|nginx|postgres" | head -10

echo ""
echo "Common fixes:"
echo "- If disk full: Clean up with 'docker system prune -a'"
echo "- If memory full: 'systemctl restart docker'"
echo "- If database corrupted: Restore from backup"
echo "- If config issues: cd /opt/btcpayserver-docker && ./btcpay-setup.sh -i"