#!/bin/bash
# Pre-start check for backend service
# Ensures port 8080 is free before starting

PORT=8080
SERVICE_NAME="church-music-backend"

# Check if port is in use
if sudo lsof -ti :$PORT &>/dev/null; then
    echo "Port $PORT is in use. Attempting to free it..."
    
    # Get all PIDs using the port
    PIDS=$(sudo lsof -ti :$PORT)
    
    for PID in $PIDS; do
        CMD=$(ps -p $PID -o comm= 2>/dev/null)
        
        # Don't kill if it's already this service (shouldn't happen, but be safe)
        if systemctl status $SERVICE_NAME 2>/dev/null | grep -q "Main PID: $PID"; then
            echo "Process $PID is already the $SERVICE_NAME service"
            exit 1
        fi
        
        echo "Killing process $PID ($CMD) on port $PORT"
        sudo kill -9 $PID 2>/dev/null || true
    done
    
    sleep 1
    
    # Verify port is now free
    if sudo lsof -ti :$PORT &>/dev/null; then
        echo "ERROR: Port $PORT still in use after cleanup"
        exit 1
    fi
    
    echo "Port $PORT is now free"
fi

exit 0
