#!/bin/bash

# Diagnostic script for AirwavePBX

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "========================================="
echo "AirwavePBX Diagnostics"
echo "========================================="
echo

# Load environment if exists
if [ -f /etc/airwavepbx/airwavepbx.env ]; then
    source /etc/airwavepbx/airwavepbx.env
    echo -e "${GREEN}[OK]${NC} Environment file loaded"
    echo "Domain: $DOMAIN"
else
    echo -e "${RED}[ERROR]${NC} Environment file not found"
fi

echo
echo "=== Service Status ==="
pm2 list

echo
echo "=== Port Checks ==="
echo -e "${BLUE}Checking listening ports:${NC}"
netstat -tuln | grep -E ":(3000|3001|80|443) " || echo "No services found on expected ports"

echo
echo "=== Process Checks ==="
echo -e "${BLUE}Node processes:${NC}"
ps aux | grep node | grep -v grep || echo "No node processes found"

echo
echo "=== Local Connectivity Test ==="
echo -e "${BLUE}Testing localhost:3000${NC}"
curl -I http://localhost:3000 2>&1 | head -n 10

echo
echo -e "${BLUE}Testing localhost:3001/api${NC}"
curl -I http://localhost:3001/api 2>&1 | head -n 10

echo
echo "=== Nginx Status ==="
sudo nginx -t
systemctl status nginx --no-pager | head -n 10

echo
echo "=== Recent PM2 Logs ==="
echo -e "${BLUE}Frontend logs:${NC}"
pm2 logs airwavepbx-frontend --lines 10 --nostream

echo
echo -e "${BLUE}API logs:${NC}"
pm2 logs airwavepbx-api --lines 10 --nostream

echo
echo "=== File Checks ==="
if [ -f /opt/airwavepbx/.next/BUILD_ID ]; then
    echo -e "${GREEN}[OK]${NC} Next.js build found"
else
    echo -e "${RED}[ERROR]${NC} Next.js build not found - application may not be built"
fi

if [ -f /opt/airwavepbx/api/server.js ]; then
    echo -e "${GREEN}[OK]${NC} API server file found"
else
    echo -e "${RED}[ERROR]${NC} API server file not found"
fi

echo
echo "=== Recommendations ==="
if ! netstat -tuln | grep -q ":3000 "; then
    echo -e "${RED}[!]${NC} Frontend not listening on port 3000"
    echo "    Try: pm2 restart airwavepbx-frontend"
fi

if ! netstat -tuln | grep -q ":3001 "; then
    echo -e "${RED}[!]${NC} API not listening on port 3001"
    echo "    Try: pm2 restart airwavepbx-api"
fi

echo
echo "=== Quick Fixes ==="
echo "1. Restart all services: pm2 restart all"
echo "2. Check logs: pm2 logs"
echo "3. Rebuild if needed: cd /opt/airwavepbx && npm run build"
echo "4. Check DNS: dig $DOMAIN"