#!/bin/bash
# ==========================================
# SSH 反向隧道启动脚本 (Windows Git Bash)
# 双击运行即可建立隧道
# ==========================================

SERVER="82.29.54.80"
TUNNEL_PORT=26000
LOCAL_PORT=22

echo "=== SSH 反向隧道 ==="
echo ""

# 检查是否已有隧道进程
if pgrep -f "ssh.*-R.*${TUNNEL_PORT}:localhost:${LOCAL_PORT}" > /dev/null 2>&1; then
    echo "[!] 隧道已在运行中"
    echo ""
    echo "如需重启，请先执行:"
    echo "  pkill -f 'ssh.*-R.*${TUNNEL_PORT}'"
    echo ""
    read -p "按回车键退出..."
    exit 0
fi

# 启动隧道 (带 KeepAlive 防断开)
echo "[*] 正在建立隧道..."
echo "    本地 :22 -> 服务器 :${TUNNEL_PORT}"
echo ""

ssh -N \
    -o "ServerAliveInterval=30" \
    -o "ServerAliveCountMax=3" \
    -o "ExitOnForwardFailure=yes" \
    -R ${TUNNEL_PORT}:localhost:${LOCAL_PORT} \
    root@${SERVER} &

SSH_PID=$!
sleep 3

# 检查是否成功
if kill -0 $SSH_PID 2>/dev/null; then
    echo "[OK] 隧道建立成功!"
    echo ""
    echo "Mac 连接命令:"
    echo "  ssh -p ${TUNNEL_PORT} Administrator@${SERVER}"
    echo ""
    echo "隧道将在后台保持运行"
    echo "关闭此窗口不影响隧道"
else
    echo "[FAIL] 隧道建立失败"
    echo "请检查网络连接和 SSH 密钥配置"
fi

echo ""
read -p "按回车键关闭此窗口..."
