#!/bin/bash
# 26002 隧道启动脚本（带日志）

SERVER="82.29.54.80"
PORT=26002
LOG_FILE="$HOME/Desktop/tunnel-26002.log"

# 清空旧日志
> "$LOG_FILE"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "=== 隧道启动脚本 ==="
log "服务器: $SERVER"
log "端口: $PORT"
log "日志: $LOG_FILE"
echo ""

log "=== 步骤1: 清理服务器端口 ==="
ssh root@$SERVER "pkill -f 'sshd.*$PORT' 2>/dev/null; sleep 2" >> "$LOG_FILE" 2>&1
log "服务器端口已清理"
echo ""

log "=== 步骤2: 启动隧道 ==="
ssh -N \
    -o "ServerAliveInterval=30" \
    -o "ServerAliveCountMax=3" \
    -o "ExitOnForwardFailure=yes" \
    -o "StrictHostKeyChecking=no" \
    -R $PORT:localhost:22 \
    root@$SERVER >> "$LOG_FILE" 2>&1 &

PID=$!
log "隧道进程 PID: $PID"
log "等待隧道建立 (5秒)..."
sleep 5
echo ""

log "=== 步骤3: 验证隧道 ==="
if kill -0 $PID 2>/dev/null; then
    log "✓ 隧道进程运行正常"
    ps -p $PID -o pid,cmd | tee -a "$LOG_FILE"
    echo ""
    log "=== Mac 连接命令 ==="
    log "  ssh -p $PORT houzi@$SERVER"
    echo ""
    log "=== 管理命令 ==="
    log "  查看日志: cat $LOG_FILE"
    log "  停止隧道: kill $PID"
    log "  检查状态: ps -p $PID"
else
    log "✗ 隧道启动失败"
    log "查看详细日志: cat $LOG_FILE"
    exit 1
fi
