#!/bin/bash

# TechIRCd Shutdown Test Script
echo "=== TechIRCd Shutdown Test ==="
echo

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

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

# Test connection
echo "Testing initial connection..."
timeout 5s bash -c '
    exec 3<>/dev/tcp/localhost/6667
    echo "NICK TestUser" >&3
    echo "USER testuser 0 * :Test User" >&3
    sleep 2
    echo "PING :test" >&3
    read -t 3 response <&3
    echo "Response: $response"
    exec 3<&-
    exec 3>&-
' && echo "✅ Connection test passed" || echo "❌ Connection test failed"

echo
echo "Testing graceful shutdown (SIGTERM)..."
echo "Sending SIGTERM to server..."

# Send SIGTERM and monitor for graceful shutdown
kill -TERM $SERVER_PID

# Wait up to 15 seconds for graceful 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 $i seconds"
        echo
        echo "=== Shutdown Test Complete ==="
        exit 0
    fi
    sleep 1
    echo -n "."
done

echo
echo "⚠️  Server did not shut down gracefully within $TIMEOUT seconds"
echo "Forcing shutdown..."
kill -9 $SERVER_PID 2>/dev/null

echo
echo "=== Shutdown Test Complete ==="
