#!/bin/bash
# Robust cleanup script for shoes/sing-box test processes

echo "=== Starting comprehensive cleanup ==="

# Kill by process name (all instances)
echo "Killing processes by name..."
killall -9 cargo 2>/dev/null || true
killall -9 shoes 2>/dev/null || true
killall -9 sing-box 2>/dev/null || true

# Kill by pattern (catches more variations)
echo "Killing processes by pattern..."
pkill -9 -f "cargo test.*vless_integration" 2>/dev/null || true
pkill -9 -f "shoes.*--no-reload" 2>/dev/null || true
pkill -9 -f "sing-box run" 2>/dev/null || true

# Kill processes using specific test ports
echo "Killing processes using test ports..."
for port in 10804 10806 18083 18086; do
    fuser -k -9 $port/tcp 2>/dev/null || true
done

# Kill any remaining cargo/shoes/sing-box processes by PID
echo "Finding and killing remaining processes..."
ps aux | grep -E "(cargo|shoes|sing-box)" | grep -v grep | grep -v cleanup_tests.sh | awk '{print $2}' | xargs -r kill -9 2>/dev/null || true

# Wait for ports to be released
echo "Waiting for ports to be released..."
sleep 5

# Verify cleanup
echo "Checking for remaining processes..."
remaining=$(ps aux | grep -E "(cargo.*test|shoes.*--no-reload|sing-box run)" | grep -v grep | grep -v cleanup_tests.sh | wc -l)

if [ "$remaining" -gt 0 ]; then
    echo "WARNING: $remaining processes still running:"
    ps aux | grep -E "(cargo.*test|shoes.*--no-reload|sing-box run)" | grep -v grep | grep -v cleanup_tests.sh
    echo "Attempting final cleanup..."
    ps aux | grep -E "(cargo.*test|shoes.*--no-reload|sing-box run)" | grep -v grep | grep -v cleanup_tests.sh | awk '{print $2}' | xargs -r kill -9 2>/dev/null || true
    sleep 3
else
    echo "✓ All test processes successfully cleaned up!"
fi

echo "=== Cleanup complete ==="
