#!/bin/bash
# ==========================================
# SSH 隧道状态检查脚本
# ==========================================

SERVER="82.29.54.80"
TUNNEL_PORT=26000
LOCAL_PORT=22

echo "=== SSH 隧道状态检查 ==="
echo ""

# 检查本地隧道进程
echo "[1/4] 检查本地隧道进程..."
TUNNEL_PID=$(pgrep -f "ssh.*-R.*${TUNNEL_PORT}:localhost:${LOCAL_PORT}")

if [ -n "$TUNNEL_PID" ]; then
    echo "✓ 隧道进程运行中"
    echo "  PID: $TUNNEL_PID"

    # 显示进程详情
    ps -p $TUNNEL_PID -o pid,etime,cmd | tail -1 | while read pid etime cmd; do
        echo "  运行时长: $etime"
    done
else
    echo "✗ 隧道进程未运行"
    echo ""
    echo "请运行 start-tunnel.sh 启动隧道"
    echo ""
    read -p "按回车键退出..."
    exit 1
fi
echo ""

# 检查本地 SSH 服务
echo "[2/4] 检查本地 SSH 服务..."
if netstat -an | grep ":${LOCAL_PORT}.*LISTENING" > /dev/null 2>&1; then
    echo "✓ SSH 服务运行中 (端口 ${LOCAL_PORT})"
else
    echo "✗ SSH 服务未运行"
    echo ""
    echo "请运行 setup-ssh.ps1 配置 SSH"
fi
echo ""

# 检查服务器连接
echo "[3/4] 检查服务器连接..."
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${SERVER} "echo OK" > /dev/null 2>&1; then
    echo "✓ 服务器连接正常"
else
    echo "✗ 无法连接到服务器"
fi
echo ""

# 检查远程端口
echo "[4/4] 检查远程端口监听..."
REMOTE_CHECK=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${SERVER} \
    "netstat -tln 2>/dev/null | grep ':${TUNNEL_PORT}' || ss -tln | grep ':${TUNNEL_PORT}'" 2>/dev/null)

if [ -n "$REMOTE_CHECK" ]; then
    echo "✓ 服务器端口 ${TUNNEL_PORT} 正在监听"
    echo ""
    echo "=== 隧道状态：正常 ==="
    echo ""
    echo "Mac 可以通过以下命令连接："
    echo "  ssh -p ${TUNNEL_PORT} Administrator@${SERVER}"
else
    echo "✗ 服务器端口 ${TUNNEL_PORT} 未监听"
    echo ""
    echo "可能原因："
    echo "  1. 隧道刚启动，尚未建立"
    echo "  2. 服务器 GatewayPorts 未开启"
    echo "  3. 隧道连接已断开"
    echo ""
    echo "建议："
    echo "  1. 等待 5-10 秒后重新检查"
    echo "  2. 运行 stop-tunnel.sh 后重新启动"
    echo "  3. 运行 diagnose.ps1 进行诊断"
fi

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