#!/bin/bash

# AirwavePBX Debug Script
# This script helps diagnose issues with AirwavePBX service failures

echo "========================================"
echo "AirwavePBX Debugging Script"
echo "========================================"
echo ""

# Function to check if running as root
check_root() {
    if [ "$EUID" -ne 0 ]; then 
        echo "⚠️  This script should be run as root for full access to logs and services"
        echo "   Continuing with limited permissions..."
        echo ""
    fi
}

# Check if we're root
check_root

# 1. Check if AirwavePBX is installed
echo "1. Checking AirwavePBX installation..."
echo "----------------------------------------"
if [ -d "/opt/airwavepbx" ]; then
    echo "✓ AirwavePBX directory exists at /opt/airwavepbx"
else
    echo "✗ AirwavePBX directory NOT FOUND at /opt/airwavepbx"
    exit 1
fi
echo ""

# 2. Check service status
echo "2. Checking service status..."
echo "----------------------------------------"
sudo systemctl status airwavepbx --no-pager
echo ""

# 3. Check error logs
echo "3. Checking error logs (last 50 lines)..."
echo "----------------------------------------"
if [ -f "/var/log/airwavepbx/error.log" ]; then
    echo "Error log contents:"
    sudo tail -50 /var/log/airwavepbx/error.log
else
    echo "✗ Error log not found at /var/log/airwavepbx/error.log"
fi
echo ""

# 4. Check system logs for airwavepbx
echo "4. Checking system logs for airwavepbx..."
echo "----------------------------------------"
sudo journalctl -u airwavepbx -n 50 --no-pager
echo ""

# 5. Check required files
echo "5. Checking required files..."
echo "----------------------------------------"
REQUIRED_FILES=(
    "/opt/airwavepbx/backend/src/index.js"
    "/opt/airwavepbx/backend/package.json"
    "/opt/airwavepbx/backend/.env"
    "/opt/airwavepbx/frontend/dist/index.html"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "$file" ]; then
        echo "✓ Found: $file"
    else
        echo "✗ Missing: $file"
    fi
done
echo ""

# 6. Check directory permissions
echo "6. Checking directory permissions..."
echo "----------------------------------------"
DIRS_TO_CHECK=(
    "/opt/airwavepbx"
    "/opt/airwavepbx/backend"
    "/opt/airwavepbx/frontend"
    "/var/log/airwavepbx"
    "/opt/airwavepbx/data"
)

for dir in "${DIRS_TO_CHECK[@]}"; do
    if [ -d "$dir" ]; then
        echo "$dir:"
        ls -ld "$dir" | awk '{print "  Owner: " $3 ", Group: " $4 ", Permissions: " $1}'
    else
        echo "✗ Directory not found: $dir"
    fi
done
echo ""

# 7. Check Node.js version
echo "7. Checking Node.js version..."
echo "----------------------------------------"
if command -v node &> /dev/null; then
    NODE_VERSION=$(node --version)
    echo "Node.js version: $NODE_VERSION"
    
    # Check if version is 18 or higher
    MAJOR_VERSION=$(echo $NODE_VERSION | cut -d. -f1 | sed 's/v//')
    if [ "$MAJOR_VERSION" -ge 18 ]; then
        echo "✓ Node.js version is compatible (18+)"
    else
        echo "✗ Node.js version is too old. Version 18+ required."
    fi
else
    echo "✗ Node.js is not installed"
fi
echo ""

# 8. Try running Node.js directly
echo "8. Testing direct Node.js execution..."
echo "----------------------------------------"
echo "Attempting to start the application directly..."
echo "(Press Ctrl+C after seeing the error)"
echo ""

cd /opt/airwavepbx/backend 2>/dev/null
if [ $? -eq 0 ]; then
    # Run for 5 seconds to capture startup errors
    timeout 5s sudo -u airwavepbx node src/index.js 2>&1 | head -50
    
    if [ ${PIPESTATUS[0]} -eq 124 ]; then
        echo ""
        echo "Note: Process was terminated after 5 seconds (this is normal for the test)"
    fi
else
    echo "✗ Could not change to /opt/airwavepbx/backend directory"
fi
echo ""

# 9. Check npm dependencies
echo "9. Checking npm dependencies..."
echo "----------------------------------------"
cd /opt/airwavepbx/backend 2>/dev/null
if [ $? -eq 0 ]; then
    if [ -d "node_modules" ]; then
        echo "✓ node_modules directory exists"
        
        # Check for specific problematic modules
        CRITICAL_MODULES=(
            "express"
            "socket.io"
            "sequelize"
            "dotenv"
        )
        
        echo "Checking critical modules:"
        for module in "${CRITICAL_MODULES[@]}"; do
            if [ -d "node_modules/$module" ]; then
                echo "  ✓ $module installed"
            else
                echo "  ✗ $module NOT installed"
            fi
        done
    else
        echo "✗ node_modules directory not found - dependencies may not be installed"
    fi
else
    echo "✗ Could not check dependencies"
fi
echo ""

# 10. Check database connectivity
echo "10. Checking database configuration..."
echo "----------------------------------------"
if [ -f "/opt/airwavepbx/backend/.env" ]; then
    echo "Checking for database configuration in .env:"
    sudo grep -E "^(DB_|DATABASE_)" /opt/airwavepbx/backend/.env | sed 's/=.*/=***/' || echo "No database configuration found"
else
    echo "✗ .env file not found"
fi
echo ""

# 11. Check port availability
echo "11. Checking port availability..."
echo "----------------------------------------"
DEFAULT_PORTS=(3000 3001 5000 8080)
echo "Checking common ports:"
for port in "${DEFAULT_PORTS[@]}"; do
    if sudo lsof -i :$port &>/dev/null; then
        echo "  ✗ Port $port is already in use by:"
        sudo lsof -i :$port | grep LISTEN | head -1
    else
        echo "  ✓ Port $port is available"
    fi
done
echo ""

# 12. Summary and recommendations
echo "========================================"
echo "SUMMARY AND RECOMMENDATIONS"
echo "========================================"
echo ""
echo "Based on the above checks:"
echo ""

# Provide specific recommendations based on findings
if [ ! -d "/opt/airwavepbx/backend/node_modules" ]; then
    echo "⚠️  Node modules not installed. Run:"
    echo "   cd /opt/airwavepbx/backend && sudo -u airwavepbx npm install"
    echo ""
fi

if [ ! -f "/opt/airwavepbx/backend/.env" ]; then
    echo "⚠️  Environment file missing. Create it:"
    echo "   sudo cp /opt/airwavepbx/backend/.env.example /opt/airwavepbx/backend/.env"
    echo "   sudo chown airwavepbx:airwavepbx /opt/airwavepbx/backend/.env"
    echo "   Then edit it with your configuration"
    echo ""
fi

echo "To get more detailed error information, you can also run:"
echo "  sudo -u airwavepbx NODE_ENV=development node /opt/airwavepbx/backend/src/index.js"
echo ""
echo "========================================"
echo "Debug script completed"
echo "========================================"