#!/bin/bash
# Port Availability Checker
# Checks if a specific port is available and suggests alternatives

set -e

if [ $# -eq 0 ]; then
    echo "Usage: $0 <port> [alternative_port1] [alternative_port2] ..."
    echo "Example: $0 8080 8081 8082"
    exit 1
fi

TARGET_PORT=$1
shift
ALTERNATIVE_PORTS=("$@")

echo "🔍 Checking port $TARGET_PORT availability..."

if lsof -i :$TARGET_PORT > /dev/null 2>&1; then
    echo "❌ Port $TARGET_PORT is already in use"
    echo ""
    
    # Show what's using the port
    echo "📋 Process using port $TARGET_PORT:"
    lsof -i :$TARGET_PORT
    echo ""
    
    # Suggest alternatives
    if [ ${#ALTERNATIVE_PORTS[@]} -gt 0 ]; then
        echo "💡 Alternative ports to try:"
        for alt_port in "${ALTERNATIVE_PORTS[@]}"; do
            if lsof -i :$alt_port > /dev/null 2>&1; then
                echo "   ❌ $alt_port - in use"
            else
                echo "   ✅ $alt_port - available"
            fi
        done
    else
        echo "💡 Try these alternative ports:"
        for alt_port in 8081 8082 8083 8888 9090; do
            if lsof -i :$alt_port > /dev/null 2>&1; then
                echo "   ❌ $alt_port - in use"
            else
                echo "   ✅ $alt_port - available"
                break
            fi
        done
    fi
    
    echo ""
    echo "🔧 To free up port $TARGET_PORT:"
    echo "   kill -9 \$(lsof -ti :$TARGET_PORT)"
    echo "   (Be careful - this will terminate the process using the port)"
    
    exit 1
else
    echo "✅ Port $TARGET_PORT is available"
    exit 0
fi