#!/bin/bash
# 修复 shell request failed 权限问题

echo "=== 修复 SSH Shell 权限问题 ==="
echo ""

# 1. 设置用户默认shell为Git Bash
echo "步骤 1/4: 设置默认shell"
BASH_PATH="/c/Program Files/Git/bin/bash.exe"
if [ -f "$BASH_PATH" ]; then
    echo "✓ Git Bash 路径: $BASH_PATH"
else
    echo "✗ 未找到 Git Bash"
    BASH_PATH="/bin/bash"
fi
echo ""

# 2. 修复 .ssh 目录权限
echo "步骤 2/4: 修复 .ssh 目录权限"
icacls.exe "C:\\Users\\houzi\\.ssh" //inheritance:r > /dev/null 2>&1
icacls.exe "C:\\Users\\houzi\\.ssh" //grant "houzi:(OI)(CI)F" > /dev/null 2>&1
icacls.exe "C:\\Users\\houzi\\.ssh" //grant "SYSTEM:(OI)(CI)F" > /dev/null 2>&1
echo "✓ .ssh 目录权限已修复"
echo ""

# 3. 修复 authorized_keys 权限
echo "步骤 3/4: 修复 authorized_keys 权限"
icacls.exe "C:\\Users\\houzi\\.ssh\\authorized_keys" //inheritance:r > /dev/null 2>&1
icacls.exe "C:\\Users\\houzi\\.ssh\\authorized_keys" //grant "houzi:(F)" > /dev/null 2>&1
icacls.exe "C:\\Users\\houzi\\.ssh\\authorized_keys" //grant "SYSTEM:(F)" > /dev/null 2>&1
echo "✓ authorized_keys 权限已修复"
echo ""

# 4. 检查并修复 sshd_config
echo "步骤 4/4: 检查 sshd_config"
SSHD_CONFIG="/c/ProgramData/ssh/sshd_config"

# 确保 PubkeyAuthentication 开启
if ! grep -q "^PubkeyAuthentication yes" "$SSHD_CONFIG"; then
    echo "PubkeyAuthentication yes" >> "$SSHD_CONFIG"
    echo "✓ 启用 PubkeyAuthentication"
fi

# 确保 PasswordAuthentication 开启（临时调试）
if ! grep -q "^PasswordAuthentication yes" "$SSHD_CONFIG"; then
    sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' "$SSHD_CONFIG"
    echo "✓ 启用 PasswordAuthentication"
fi

# 确保没有 StrictModes（严格权限检查可能导致问题）
if grep -q "^StrictModes yes" "$SSHD_CONFIG"; then
    sed -i 's/^StrictModes yes/StrictModes no/' "$SSHD_CONFIG"
    echo "✓ 禁用 StrictModes"
fi
echo ""

# 5. 重启 SSH Server
echo "步骤 5/4: 重启 SSH Server"
net.exe stop sshd > /dev/null 2>&1
sleep 2
net.exe start sshd > /dev/null 2>&1
echo "✓ SSH Server 已重启"
echo ""

echo "=== 修复完成 ==="
echo ""
echo "立即测试："
echo "1. 本地测试: ssh houzi@127.0.0.1"
echo "2. Mac 测试: ssh -p 26002 houzi@82.29.54.80"
