#!/bin/bash
# Windows 初始化脚本 - 在 Windows Git Bash 执行
# 功能: 安装 OpenSSH Server + 配置密钥 + 建立反向隧道

set -e

SERVER="${SSH_SERVER:-82.29.54.80}"
TUNNEL_PORT="${SSH_TUNNEL_PORT:-26000}"

echo "=== Windows 远程控制初始化 ==="
echo ""
echo "服务器: $SERVER"
echo "隧道端口: $TUNNEL_PORT"
echo ""

# Step 1: 下载并安装 OpenSSH Server
echo "[1/5] 安装 OpenSSH Server..."

if powershell.exe -Command "Get-Service sshd -ErrorAction SilentlyContinue" 2>/dev/null | grep -q "Running"; then
    echo "✓ SSH Server 已安装并运行"
else
    echo "  下载 OpenSSH..."
    cd ~/Desktop
    curl -L -o openssh.zip https://github.com/PowerShell/Win32-OpenSSH/releases/download/10.0.0.0p2-Preview/OpenSSH-Win64.zip
    unzip -o openssh.zip

    echo "  安装中 (会弹出管理员窗口，请点'是')..."
    powershell.exe -Command "Start-Process powershell -Verb RunAs -Wait -ArgumentList '-Command cd C:\\Users\\Administrator\\Desktop\\OpenSSH-Win64; .\\install-sshd.ps1; Start-Service sshd; Set-Service sshd -StartupType Automatic'"

    # 验证
    sleep 3
    if powershell.exe -Command "Get-Service sshd" 2>/dev/null | grep -q "Running"; then
        echo "✓ SSH Server 安装成功"
    else
        echo "✗ SSH Server 安装失败"
        exit 1
    fi
fi

# Step 2: 生成 SSH 密钥
echo ""
echo "[2/5] 配置 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/5] 添加公钥到服务器 (首次需输入服务器密码)..."
cat ~/.ssh/id_rsa.pub | ssh root@${SERVER} "cat >> ~/.ssh/authorized_keys"
echo "✓ 公钥已添加到服务器"

# Step 4: 配置 Windows 接受服务器公钥
echo ""
echo "[4/5] 配置 Windows 接受远程连接..."
ssh root@${SERVER} "cat ~/.ssh/authorized_keys" >> ~/.ssh/authorized_keys
cat ~/.ssh/authorized_keys | powershell.exe -Command '$input | Set-Content C:\ProgramData\ssh\administrators_authorized_keys'
echo "✓ Windows authorized_keys 已配置"

# Step 5: 建立反向隧道
echo ""
echo "[5/5] 建立反向隧道..."
ssh -N -R ${TUNNEL_PORT}:localhost:22 root@${SERVER} &
sleep 2
echo "✓ 隧道已建立 (后台运行)"

echo ""
echo "=========================================="
echo "  初始化完成!"
echo "=========================================="
echo ""
echo "Mac 连接命令:"
echo "  ssh -p ${TUNNEL_PORT} Administrator@${SERVER}"
echo ""
echo "注意: Windows 重启后需重新建立隧道:"
echo "  ssh -N -R ${TUNNEL_PORT}:localhost:22 root@${SERVER} &"
