#!/bin/bash

###############################################################################
# MyClaw WSL2 权限封锁 — 独立手动版
#
# 在 WSL2 内手动运行（通常通过 myclaw restrict 从 Windows 自动调用）
#
# 功能：编辑 /etc/wsl.conf，设置 [automount] enabled = false
#
# 手动使用：
#   bash scripts/restrict-wsl-access.sh
#
###############################################################################

set -e

WSL_CONF="/etc/wsl.conf"

# 检查 WSL 环境
if [[ ! -f /proc/version ]] || ! grep -qi "microsoft\|wsl" /proc/version 2>/dev/null; then
    echo "[错误] 此脚本必须在 WSL2 环境中运行"
    exit 1
fi

# 备份
if [[ -f "$WSL_CONF" ]]; then
    sudo cp "$WSL_CONF" /etc/wsl.conf.bak
    echo "[信息] 已备份到 /etc/wsl.conf.bak"
fi

# 读取现有配置
existing=$(cat "$WSL_CONF" 2>/dev/null || echo "")

# 构建新配置
if echo "$existing" | grep -q '\[automount\]'; then
    new_content=$(echo "$existing" | sed '/\[automount\]/,/^\[/ s/enabled.*/enabled = false/')
else
    new_content="${existing}
[automount]
enabled = false
"
fi

# 用 base64 避免转义问题
echo "$new_content" | base64 -d > /dev/null 2>&1 || true
echo "$new_content" | sudo tee "$WSL_CONF" > /dev/null
sudo chmod 644 "$WSL_CONF"

# 验证
if grep -q 'enabled = false\|enabled=false' "$WSL_CONF"; then
    echo "[成功] automount 已禁用"
    echo ""
    echo "当前 /etc/wsl.conf 内容:"
    echo "---"
    sudo cat "$WSL_CONF"
    echo "---"
    echo ""
    echo "[提示] 需要重启 WSL2 才能生效: wsl --shutdown"
else
    echo "[错误] 配置写入失败"
    exit 1
fi
