#!/bin/bash

echo "=== AirwavePBX 502 Error Diagnostic ==="
echo

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

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

echo "3. Checking if port 3001 is listening:"
netstat -tlnp | grep 3001 || echo "Port 3001 not listening!"
echo

echo "4. Checking Node.js installation:"
which node && node --version || echo "Node.js not found!"
echo

echo "5. Checking if airwave user exists:"
id airwave || echo "airwave user not found!"
echo

echo "6. Checking AirwavePBX directory:"
ls -la /opt/airwavepbx/ | head -10
echo

echo "7. Checking for package.json:"
ls -la /opt/airwavepbx/package.json
echo

echo "8. Checking for node_modules:"
ls -la /opt/airwavepbx/node_modules/ | head -5
echo

echo "9. Testing direct API access:"
curl -s http://localhost:3001/api/system/stats || echo "API not responding!"
echo

echo "10. Nginx error log (last 10 lines):"
tail -10 /var/log/nginx/error.log
echo

echo "=== Diagnostic complete ==="