#!/bin/bash
# Windows 远程控制初始化脚本 - 在 Git Bash 中执行

set -e

SERVER="82.29.54.80"
SERVER_USER="root"
WIN_SSH_PORT=22
TUNNEL_PORT=26000

echo "=== Windows 远程控制初始化 ==="
echo ""

# Step 1: 启用 Windows OpenSSH Server
echo "[1/4] 启用 Windows OpenSSH Server..."
powershell.exe -Command "Start-Process powershell -Verb RunAs -ArgumentList '-Command', 'Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0; Start-Service sshd; Set-Service -Name sshd -StartupType Automatic'"

echo "等待 SSH 服务启动..."
sleep 5

# 验证 SSH 服务
if powershell.exe -Command "Get-Service sshd" | grep -q "Running"; then
    echo "✓ SSH Server 已启动"
else
    echo "✗ SSH Server 启动失败，请手动检查"
    exit 1
fi

# Step 2: 生成 SSH 密钥
echo ""
echo "[2/4] 配置 SSH 密钥..."
if [ ! -f ~/.ssh/id_rsa ]; then
    ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/id_rsa
    echo "✓ SSH 密钥已生成"
else
    echo "✓ SSH 密钥已存在"
fi

# Step 3: 添加公钥到服务器
echo ""
echo "[3/4] 添加公钥到服务器 $SERVER..."
echo "需要输入服务器密码 (Zhxc6545398):"
cat ~/.ssh/id_rsa.pub | ssh ${SERVER_USER}@${SERVER} "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
echo "✓ 公钥已添加"

# Step 4: 创建反向隧道启动脚本
echo ""
echo "[4/4] 创建反向隧道脚本..."

cat > ~/start-tunnel.sh << 'EOF'
#!/bin/bash
SERVER="82.29.54.80"
TUNNEL_PORT=26000
echo "建立反向隧道到 $SERVER:$TUNNEL_PORT ..."
ssh -N -R ${TUNNEL_PORT}:localhost:22 root@${SERVER} &
echo "隧道已建立 (后台运行)"
echo "Mac 可通过以下命令连接:"
echo "  ssh -p ${TUNNEL_PORT} Administrator@${SERVER}"
EOF
chmod +x ~/start-tunnel.sh

echo ""
echo "=== 初始化完成 ==="
echo ""
echo "下一步: 执行 ~/start-tunnel.sh 启动隧道"
echo "然后 Mac 端执行: ssh -p $TUNNEL_PORT Administrator@$SERVER"
