#!/bin/bash
# =============================================================================
# Presence Service - Stop Service Script
# =============================================================================
# Gracefully stops the Presence Service running on port 3011.
# =============================================================================

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

echo -e "${YELLOW}🛑 Stopping Presence Service...${NC}"

# Find process listening on port 3011
if command -v lsof &> /dev/null; then
    PID=$(lsof -ti :3011 2>/dev/null)
elif command -v netstat &> /dev/null; then
    PID=$(netstat -tlnp 2>/dev/null | grep :3011 | awk '{print $7}' | cut -d'/' -f1)
else
    echo -e "${YELLOW}⚠️  Cannot find process (lsof/netstat not available)${NC}"
    echo "Try: pkill -f 'node.*presence'"
    exit 1
fi

if [ -z "$PID" ]; then
    echo -e "${YELLOW}⚠️  Presence Service is not running${NC}"
    exit 0
fi

echo "Found process: PID=$PID"

# Try graceful shutdown first
echo "Sending SIGTERM signal..."
kill $PID 2>/dev/null

# Wait for process to exit
for i in {1..10}; do
    if ! kill -0 $PID 2>/dev/null; then
        echo -e "${GREEN}✓ Presence Service stopped gracefully${NC}"
        exit 0
    fi
    sleep 1
    echo -n "."
done

echo ""
echo -e "${YELLOW}⚠️  Process not responding, forcing shutdown...${NC}"
kill -9 $PID 2>/dev/null

if ! kill -0 $PID 2>/dev/null; then
    echo -e "${GREEN}✓ Presence Service forcefully stopped${NC}"
else
    echo -e "${RED}✗ Failed to stop process${NC}"
    exit 1
fi
