#!/bin/bash
# Port Cleanup Script - Kill any processes using critical ports
# This prevents port conflicts when starting services

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║              Port Cleanup & Conflict Resolution                ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

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

# Ports to check
BACKEND_PORT=8080
FRONTEND_PORT=5100

# Function to check and kill process on a port
cleanup_port() {
    local port=$1
    local service_name=$2
    
    echo "Checking port $port ($service_name)..."
    
    # Find process using the port
    local pids=$(sudo lsof -ti :$port 2>/dev/null)
    
    if [ -z "$pids" ]; then
        echo -e "${GREEN}✓ Port $port is free${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}⚠ Port $port is in use by PID(s): $pids${NC}"
    
    # Get process details
    for pid in $pids; do
        local cmd=$(ps -p $pid -o comm= 2>/dev/null)
        local full_cmd=$(ps -p $pid -o args= 2>/dev/null)
        echo "  Process: $cmd (PID $pid)"
        echo "  Command: $full_cmd"
        
        # Check if it's a systemd service
        if systemctl status church-music-backend.service 2>/dev/null | grep -q "Main PID: $pid"; then
            echo -e "${YELLOW}  This is the systemd backend service - use 'systemctl stop' instead${NC}"
            continue
        fi
        
        if systemctl status church-music-frontend.service 2>/dev/null | grep -q "Main PID: $pid"; then
            echo -e "${YELLOW}  This is the systemd frontend service - use 'systemctl stop' instead${NC}"
            continue
        fi
        
        # Kill the rogue process
        echo "  Killing process $pid..."
        sudo kill -9 $pid 2>/dev/null
        
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}  ✓ Process $pid killed${NC}"
        else
            echo -e "${RED}  ✗ Failed to kill process $pid${NC}"
        fi
    done
    
    # Verify port is now free
    sleep 1
    if sudo lsof -ti :$port &>/dev/null; then
        echo -e "${RED}✗ Port $port still in use after cleanup${NC}"
        return 1
    else
        echo -e "${GREEN}✓ Port $port is now free${NC}"
        return 0
    fi
}

# Clean up PID files from development mode
cleanup_pid_files() {
    echo ""
    echo "Cleaning up stale PID files..."
    
    if [ -f /tmp/church-backend.pid ]; then
        local pid=$(cat /tmp/church-backend.pid)
        if ! ps -p $pid > /dev/null 2>&1; then
            rm /tmp/church-backend.pid
            echo -e "${GREEN}✓ Removed stale backend PID file${NC}"
        fi
    fi
    
    if [ -f /tmp/church-frontend.pid ]; then
        local pid=$(cat /tmp/church-frontend.pid)
        if ! ps -p $pid > /dev/null 2>&1; then
            rm /tmp/church-frontend.pid
            echo -e "${GREEN}✓ Removed stale frontend PID file${NC}"
        fi
    fi
}

# Kill any webpack dev servers or react-scripts
cleanup_dev_servers() {
    echo ""
    echo "Checking for development servers..."
    
    local react_pids=$(pgrep -f "react-scripts start" 2>/dev/null)
    if [ -n "$react_pids" ]; then
        echo -e "${YELLOW}⚠ Found React dev server processes${NC}"
        for pid in $react_pids; do
            echo "  Killing react-scripts (PID $pid)"
            kill -9 $pid 2>/dev/null || true
        done
        echo -e "${GREEN}✓ React dev servers killed${NC}"
    fi
    
    local webpack_pids=$(pgrep -f "webpack-dev-server" 2>/dev/null)
    if [ -n "$webpack_pids" ]; then
        echo -e "${YELLOW}⚠ Found webpack-dev-server processes${NC}"
        for pid in $webpack_pids; do
            echo "  Killing webpack-dev-server (PID $pid)"
            kill -9 $pid 2>/dev/null || true
        done
        echo -e "${GREEN}✓ Webpack dev servers killed${NC}"
    fi
    
    if [ -z "$react_pids" ] && [ -z "$webpack_pids" ]; then
        echo -e "${GREEN}✓ No development servers found${NC}"
    fi
}

# Main execution
echo "Starting port cleanup..."
echo ""

cleanup_port $BACKEND_PORT "Backend API"
echo ""
cleanup_port $FRONTEND_PORT "Frontend Server"
echo ""
cleanup_pid_files
echo ""
cleanup_dev_servers

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║                    CLEANUP COMPLETE                            ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "You can now start the services:"
echo "  sudo systemctl start church-music-backend"
echo "  sudo systemctl start church-music-frontend"
echo ""
