#!/bin/bash
# ==========================================
# OpenSSH Server 安装脚本 (Git Bash)
# 机器: JQUSFUO
# ==========================================

set -e

SERVER="82.29.54.80"
DOWNLOAD_URL="http://${SERVER}/scripts/OpenSSH-Win64.zip"
INSTALL_DIR="/c/Program Files/OpenSSH-Win64"
TEMP_DIR="$HOME/Downloads"

echo "=== OpenSSH Server 安装 ==="
echo ""

# 1. 下载 OpenSSH-Win64.zip
echo "[1/5] 下载 OpenSSH-Win64.zip..."
cd "$TEMP_DIR"

if [ -f "OpenSSH-Win64.zip" ]; then
    echo "  文件已存在，跳过下载"
else
    curl -L -o OpenSSH-Win64.zip "$DOWNLOAD_URL"
    echo "  ✓ 下载完成 (4.7MB)"
fi
echo ""

# 2. 解压
echo "[2/5] 解压安装包..."
if [ -d "OpenSSH-Win64" ]; then
    echo "  目录已存在，删除旧版本"
    rm -rf OpenSSH-Win64
fi

unzip -q OpenSSH-Win64.zip
echo "  ✓ 解压完成"
echo ""

# 3. 移动到 Program Files (需要管理员权限)
echo "[3/5] 移动到安装目录..."
echo "  目标: $INSTALL_DIR"
echo ""
echo "  ⚠️  需要管理员权限！"
echo "  请以管理员身份打开 PowerShell，执行："
echo ""
echo "  Move-Item -Path '$TEMP_DIR\OpenSSH-Win64' -Destination 'C:\Program Files\' -Force"
echo ""
read -p "移动完成后按回车继续..."

# 4. 安装服务 (必须用 PowerShell)
echo ""
echo "[4/5] 安装 SSH Server 服务..."
echo ""
echo "  ⚠️  以下步骤必须在 PowerShell (管理员) 中执行："
echo ""
echo "  cd 'C:\Program Files\OpenSSH-Win64'"
echo "  .\install-sshd.ps1"
echo "  netsh advfirewall firewall add rule name=\"OpenSSH Server\" dir=in action=allow protocol=TCP localport=22"
echo "  Start-Service sshd"
echo "  Set-Service -Name sshd -StartupType Automatic"
echo ""
read -p "安装完成后按回车继续..."

# 5. 验证
echo ""
echo "[5/5] 验证安装..."
if netstat -an | grep -q ":22.*LISTENING"; then
    echo "  ✓ SSH Server 正在运行（端口 22 已监听）"
else
    echo "  ✗ SSH Server 未运行"
    echo ""
    echo "  请在 PowerShell (管理员) 中执行："
    echo "  Start-Service sshd"
fi

echo ""
echo "=== 安装完成 ==="
echo ""
echo "下一步："
echo "  1. 生成 SSH 密钥: ssh-keygen -t rsa -b 4096"
echo "  2. 上传公钥: cat ~/.ssh/id_rsa.pub | ssh root@82.29.54.80 \"cat >> ~/.ssh/authorized_keys\""
echo "  3. 下载隧道脚本: curl -o ~/Desktop/start-tunnel-26002.sh http://82.29.54.80/scripts/start-tunnel-26002.sh"
echo "  4. 启动隧道: bash ~/Desktop/start-tunnel-26002.sh"
echo ""
