#!/bin/bash

# TechIRCd Stability Stress Test
echo "=== TechIRCd Stability Stress Test ==="
echo "This test simulates conditions that previously caused freezing"
echo

# Start the server
echo "Starting TechIRCd..."
./techircd start &
SERVER_PID=$!

echo "Server started with PID: $SERVER_PID"
echo "Waiting 3 seconds for server to initialize..."
sleep 3

# Function to create a client connection
create_client() {
    local client_id=$1
    local duration=$2
    
    timeout ${duration}s bash -c "
        exec 3<>/dev/tcp/localhost/6667
        echo 'NICK TestUser$client_id' >&3
        echo 'USER testuser$client_id 0 * :Test User $client_id' >&3
        sleep 2
        echo 'JOIN #test' >&3
        
        # Send periodic messages to keep connection alive
        for i in {1..20}; do
            echo 'PING :client$client_id' >&3
            sleep 1
            echo 'PRIVMSG #test :Message \$i from client $client_id' >&3
            sleep 1
        done
        
        echo 'QUIT :Test complete' >&3
        exec 3<&-
        exec 3>&-
    " 2>/dev/null &
}

# Function to create unstable client (connects and disconnects quickly)
create_unstable_client() {
    local client_id=$1
    
    timeout 5s bash -c "
        exec 3<>/dev/tcp/localhost/6667
        echo 'NICK Unstable$client_id' >&3
        echo 'USER unstable$client_id 0 * :Unstable User $client_id' >&3
        sleep 1
        # Abruptly close connection without QUIT
        exec 3<&-
        exec 3>&-
    " 2>/dev/null &
}

echo "Phase 1: Testing multiple stable connections..."
# Create 10 stable clients
for i in {1..10}; do
    create_client $i 30
    echo -n "."
    sleep 0.5
done
echo " (10 stable clients created)"

echo "Phase 2: Testing unstable connections (simulating network issues)..."
# Create 20 unstable clients that disconnect abruptly
for i in {1..20}; do
    create_unstable_client $i
    echo -n "."
    sleep 0.2
done
echo " (20 unstable clients created)"

echo "Phase 3: Testing rapid connection attempts..."
# Create many short-lived connections
for i in {1..30}; do
    timeout 2s bash -c "
        exec 3<>/dev/tcp/localhost/6667
        echo 'NICK Rapid$i' >&3
        exec 3<&-
        exec 3>&-
    " 2>/dev/null &
    sleep 0.1
done
echo "30 rapid connections created"

echo
echo "Monitoring server health for 45 seconds..."
echo "Press Ctrl+C to interrupt test early"

# Monitor server for 45 seconds
for i in {1..45}; do
    if ! kill -0 $SERVER_PID 2>/dev/null; then
        echo "❌ Server died during stress test!"
        echo "=== Stress Test Failed ==="
        exit 1
    fi
    
    # Test server responsiveness every 10 seconds
    if [ $((i % 10)) -eq 0 ]; then
        echo "Testing server responsiveness at ${i}s..."
        timeout 3s bash -c '
            exec 3<>/dev/tcp/localhost/6667
            echo "NICK HealthCheck$RANDOM" >&3
            echo "USER healthcheck 0 * :Health Check" >&3
            sleep 1
            echo "QUIT :Health check complete" >&3
            exec 3<&-
            exec 3>&-
        ' 2>/dev/null && echo "✅ Server responsive" || echo "⚠️  Server response slow/failed"
    fi
    
    echo -n "."
    sleep 1
done

echo
echo "✅ Server survived 45-second stress test!"

echo "Testing graceful shutdown after stress..."
kill -TERM $SERVER_PID

# Wait for shutdown
TIMEOUT=15
for i in $(seq 1 $TIMEOUT); do
    if ! kill -0 $SERVER_PID 2>/dev/null; then
        echo "✅ Server shut down gracefully after stress test"
        echo "=== Stress Test Passed ==="
        exit 0
    fi
    sleep 1
done

echo "⚠️  Server did not shut down gracefully, forcing..."
kill -9 $SERVER_PID 2>/dev/null
echo "=== Stress Test Completed with Warning ==="
