#!/bin/bash
# kill_port.sh - 检测并杀掉占用指定端口的进程

PORT=${1:-8000}

echo "=========================================="
echo "端口检测与清理脚本"
echo "=========================================="
echo "目标端口: $PORT"
echo ""

# 检测并杀掉占用端口的进程
echo "[1/3] 检测端口 $PORT ..."
if fuser $PORT/tcp >/dev/null 2>&1; then
    echo "  ✓ 发现占用端口 $PORT 的进程:"
    fuser -v $PORT/tcp 2>&1
    
    echo ""
    echo "[2/3] 正在终止进程..."
    fuser -k $PORT/tcp 2>&1
    echo "  ✓ 进程已终止"
else
    echo "  ✓ 端口 $PORT 未被占用"
fi

echo ""
echo "[3/3] 清理残留Docker容器..."
EXIT_CONTAINERS=$(docker ps -a | grep Exit | awk '{print $1}')
if [ -n "$EXIT_CONTAINERS" ]; then
    echo "  发现残留容器，正在清理..."
    echo "$EXIT_CONTAINERS" | xargs -r docker rm -f
    echo "  ✓ 残留容器已清理"
else
    echo "  ✓ 无残留容器"
fi

echo ""
echo "=========================================="
echo "完成!"
echo "=========================================="
