#!/bin/bash

echo "=== AirwavePBX 502 Error Troubleshooting ==="
echo

echo "1. Checking if AirwavePBX service is running:"
systemctl status airwavepbx --no-pager
echo

echo "2. Checking recent logs:"
echo "--- Last 20 lines of AirwavePBX logs ---"
journalctl -u airwavepbx -n 20 --no-pager
echo

echo "3. Checking if port 3000 is listening:"
netstat -tlnp | grep :3000
echo

echo "4. Checking Node.js installation:"
which node
node --version
echo

echo "5. Checking error logs:"
echo "--- Application error log ---"
tail -20 /var/log/airwavepbx/error.log 2>/dev/null || echo "No error log found"
echo

echo "6. Checking environment file:"
if [ -f /etc/airwavepbx/config.env ]; then
    echo "Environment file exists"
    grep -E "^(NODE_ENV|PORT|DOMAIN)" /etc/airwavepbx/config.env
else
    echo "ERROR: Environment file not found!"
fi
echo

echo "7. Checking nginx configuration:"
nginx -t
echo

echo "8. Testing backend directly:"
curl -I http://localhost:3000 2>&1
echo

echo "=== Quick Fix Commands ==="
echo "To restart the service:"
echo "  systemctl restart airwavepbx"
echo
echo "To check live logs:"
echo "  journalctl -u airwavepbx -f"
echo
echo "To check if dependencies are installed:"
echo "  cd /opt/airwavepbx && npm list --depth=0"