#!/bin/bash

echo "=========================================="
echo "  Server Port Status - 192.168.10.130"
echo "=========================================="
echo ""

echo "🌐 Web Services:"
echo "----------------------------------------"
check_port() {
    local port=$1
    local service=$2
    local expected_pid=$3
    
    if ss -tln | grep -q ":$port "; then
        local process=$(sudo lsof -i :$port -t 2>/dev/null | head -1)
        local cmd=$(ps -p $process -o comm= 2>/dev/null)
        echo "  ✅ Port $port ($service) - $cmd [PID: $process]"
    else
        echo "  ❌ Port $port ($service) - NOT LISTENING"
    fi
}

check_port 80 "HTTP/nginx"
check_port 443 "HTTPS/nginx"
check_port 5000 "SkyArtShop Backend"
check_port 8080 "House of Prayer"
check_port 3000 "HOP Frontend"

echo ""
echo "💾 Database Services:"
echo "----------------------------------------"
check_port 3306 "MySQL/MariaDB"
check_port 5432 "PostgreSQL"

echo ""
echo "🔍 Checking for Port Conflicts:"
echo "----------------------------------------"

# Check for duplicate SkyArtShop instances
SKYART_COUNT=$(ps aux | grep -c "/var/www/SkyArtShop/backend/server.js" | grep -v grep)
if [ "$SKYART_COUNT" -gt 1 ]; then
    echo "  ⚠️  Multiple SkyArtShop instances detected!"
    ps aux | grep "/var/www/SkyArtShop/backend/server.js" | grep -v grep
else
    echo "  ✅ No duplicate SkyArtShop instances"
fi

# Check if port 3001 is free (should be)
if ss -tln | grep -q ":3001 "; then
    echo "  ⚠️  Port 3001 still in use (should be free)"
    sudo lsof -i :3001
else
    echo "  ✅ Port 3001 is free (old instance cleaned up)"
fi

echo ""
echo "📊 All Active Ports:"
echo "----------------------------------------"
ss -tlnp 2>/dev/null | grep LISTEN | awk '{print $4}' | grep -o "[0-9]*$" | sort -n | uniq | head -20

echo ""
echo "=========================================="
echo "  Summary"
echo "=========================================="
echo "  SkyArtShop:     Port 5000 ✓"
echo "  House of Prayer: Port 8080 ✓"
echo "  Nginx HTTPS:    Port 443 ✓"
echo "  PostgreSQL:     Port 5432 ✓"
echo ""
echo "Run this script anytime to check port status."
echo "=========================================="
