#!/bin/bash
# ==========================================
# 停止 SSH 隧道脚本
# ==========================================

SERVER="82.29.54.80"
TUNNEL_PORT=26000
LOCAL_PORT=22

echo "=== 停止 SSH 隧道 ==="
echo ""

# 查找隧道进程
TUNNEL_PIDS=$(pgrep -f "ssh.*-R.*${TUNNEL_PORT}:localhost:${LOCAL_PORT}")

if [ -z "$TUNNEL_PIDS" ]; then
    echo "[!] 没有找到运行中的隧道进程"
    echo ""
    read -p "按回车键退出..."
    exit 0
fi

# 显示找到的进程
echo "找到以下隧道进程："
echo "$TUNNEL_PIDS" | while read pid; do
    echo "  PID: $pid"
    ps -p $pid -o cmd | tail -1 | sed 's/^/    /'
done
echo ""

# 确认停止
read -p "确认停止这些进程？(y/N) " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "已取消"
    echo ""
    read -p "按回车键退出..."
    exit 0
fi

# 停止进程
echo "正在停止隧道..."
echo "$TUNNEL_PIDS" | while read pid; do
    if kill $pid 2>/dev/null; then
        echo "  ✓ 已停止 PID: $pid"
    else
        echo "  ✗ 无法停止 PID: $pid (可能需要管理员权限)"
    fi
done

# 等待进程结束
sleep 2

# 验证
REMAINING=$(pgrep -f "ssh.*-R.*${TUNNEL_PORT}:localhost:${LOCAL_PORT}")
if [ -z "$REMAINING" ]; then
    echo ""
    echo "[OK] 所有隧道已停止"
else
    echo ""
    echo "[!] 部分进程仍在运行："
    echo "$REMAINING" | while read pid; do
        echo "  PID: $pid"
    done
    echo ""
    echo "可以尝试强制停止："
    echo "  kill -9 $REMAINING"
fi

echo ""
read -p "按回车键退出..."
