#!/bin/bash

# ==========================================
# OpenClaw 全系统国内镜像一键安装脚本
# 支持: macOS, Ubuntu, Debian, Arch Linux
# ==========================================

set -e

# --- 1. 判定操作系统 ---
OS_TYPE="$(uname)"
echo "🔍 检测到系统类型: $OS_TYPE"

# --- 2. 安装 Git 和 基础环境 (使用国内镜像) ---
if [ "$OS_TYPE" = "Darwin" ]; then
    echo "🍎 [macOS] 正在通过国内镜像安装 Homebrew..."
    # 使用 HomebrewCN (执行完后会自动配置国内源)
    if ! command -v brew &> /dev/null; then
        /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"
        eval "$(/opt/homebrew/bin/brew shellenv)"
    fi
    echo "📦 安装 Git..."
    brew install git
elif [ -f /etc/debian_version ]; then
    echo "🐧 [Ubuntu/Debian] 正在配置 APT 国内镜像并安装 Git..."
    # 尝试自动替换为清华源 (仅限 Ubuntu)
    if [ -f /etc/lsb-release ]; then
        sudo sed -i 's/archive.ubuntu.com/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list
        sudo sed -i 's/security.ubuntu.com/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list
    fi
    sudo apt update
    sudo apt install -y git curl
elif [ -f /etc/arch-release ]; then
    echo "🏔️ [Arch Linux] 正在配置 TUNA 镜像并安装 Git..."
    sudo pacman -Syu --noconfirm git curl
else
    echo "❌ 暂不支持的系统，请手动安装 Git。"
    exit 1
fi

# --- 3. 安装 NVM (使用 Gitee 镜像) ---
echo "⚙️ 正在通过国内镜像安装 NVM..."
export NVM_DIR="$HOME/.nvm"
if [ ! -d "$NVM_DIR" ]; then
    # 使用国内镜像脚本安装 NVM
    git clone https://gitee.com/mirrors/nvm.git "$NVM_DIR"
    cd "$NVM_DIR" && git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)`
    cd -
fi

# 临时激活 NVM
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

# --- 4. 配置 Node 国内镜像源 (淘宝/华为源) ---
echo "⚡ 配置 Node.js 镜像源..."
export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node

# --- 5. 安装 Node 22 & 配置 npm 镜像 ---
echo "🟢 正在安装 Node 22..."
nvm install 22
nvm use 22
nvm alias default 22

echo "🚀 配置 npm 国内镜像 (npmmirror)..."
npm config set registry https://registry.npmmirror.com

# --- 6. 安装 OpenClaw ---
echo "🦀 正在安装 OpenClaw..."
# 因为使用了 NVM，这里绝对不需要 sudo
npm install -g openclaw@latest

# --- 7. 写入环境变量到 Shell 配置 ---
SHELL_RC="$HOME/.zshrc"
[ "$SHELL" = "/bin/bash" ] && SHELL_RC="$HOME/.bashrc"

echo "📝 正在同步环境变量到 $SHELL_RC ..."
cat << 'EOF' >> "$SHELL_RC"

# NVM Configuration
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node
EOF

echo "------------------------------------------"
echo "🎉 [OpenClaw] 镜像安装任务全部完成！"
echo "✅ Git: $(git --version)"
echo "✅ Node: $(node -v)"
echo "✅ npm Registry: $(npm config get registry)"
echo "✅ OpenClaw 路径: $(which openclaw)"
echo "------------------------------------------"
echo "👉 请执行 'source $SHELL_RC' 或重启终端以激活环境。"
echo "👉 然后输入 'openclaw onboard' 开始初始化。"