#!/bin/bash
set -e

# === 基本信息 ===
NVM_VERSION="0.40.3"
NVM_TAR="nvm-${NVM_VERSION}.tar.gz"
NVM_URL="https://chenziqaq.xyz/zip/${NVM_TAR}"
NODE_TAR=$(ls node-v*-linux-*.tar.* 2>/dev/null | head -n 1)
NVM_INSTALL_DIR="/usr/local/nvm-${NVM_VERSION}"
NVM_LINK_DIR="$HOME/.nvm"

echo "=============================================="
echo " 🧩 离线安装 NVM (Node Version Manager)"
echo "=============================================="

# === 0. 检查 wget 是否可用 ===
if ! command -v wget >/dev/null 2>&1; then
    echo "❌ 未检测到 wget，请执行以下命令安装："
    echo "   sudo apt install -y wget"
    exit 1
fi

# === 1. 检查或下载 NVM 包 ===
if [ ! -f "$NVM_TAR" ]; then
    echo "ℹ️ 未找到 $NVM_TAR，尝试从镜像下载 ..."
    if wget -q --show-progress "$NVM_URL"; then
        echo "✅ 已成功下载 $NVM_TAR"
    else
        echo "❌ 下载失败，请手动将 $NVM_TAR 放入当前目录"
        exit 1
    fi
else
    echo "✅ 检测到本地 NVM 包：$NVM_TAR"
fi

# === 2. 解压 NVM ===
echo "➡️ 正在解压 $NVM_TAR 到 /usr/local/ ..."
mkdir -p /usr/local/
tar -xzf "$NVM_TAR" -C /usr/local/

# === 3. 创建软链接 ~/.nvm ===
if [ -L "$NVM_LINK_DIR" ] || [ -d "$NVM_LINK_DIR" ]; then
    echo "⚠️ 检测到 $NVM_LINK_DIR 已存在，跳过软链接创建"
else
    ln -s "$NVM_INSTALL_DIR" "$NVM_LINK_DIR"
    echo "✅ 已创建软链接：$NVM_LINK_DIR -> $NVM_INSTALL_DIR"
fi

# === 4. 配置环境变量 ===
if ! grep -q 'NVM_DIR=' ~/.bashrc; then
    echo "➡️ 正在更新 ~/.bashrc ..."
    cat << 'EOF' >> ~/.bashrc

# ===== NVM 离线安装配置 =====
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
export NVM_NODEJS_ORG_MIRROR=https://npmmirror.com/mirrors/node
# =============================
EOF
    echo "✅ 已更新 ~/.bashrc"
else
    echo "⚠️ ~/.bashrc 已包含 NVM 配置，跳过修改"
fi

# === 5. 激活环境变量 ===
source ~/.bashrc
echo "✅ NVM 环境变量已加载"

# === 6. 检查是否有离线 Node 包 ===
if [ -n "$NODE_TAR" ]; then
    echo "➡️ 检测到 Node 包：$NODE_TAR"
    NODE_VERSION=$(echo "$NODE_TAR" | grep -oP 'v[0-9]+\.[0-9]+\.[0-9]+')
    NODE_DIR="$NVM_LINK_DIR/versions/node/$NODE_VERSION"
    mkdir -p "$NODE_DIR"

    echo "➡️ 解压 Node 到 $NODE_DIR ..."
    case "$NODE_TAR" in
        *.tar.xz) tar -xJf "$NODE_TAR" -C "$NODE_DIR" --strip-components=1 ;;
        *.tar.gz) tar -xzf "$NODE_TAR" -C "$NODE_DIR" --strip-components=1 ;;
        *) echo "⚠️ 未知压缩格式：$NODE_TAR" ;;
    esac

    echo "➡️ 激活 Node 版本 $NODE_VERSION ..."
    nvm use "$NODE_VERSION" || true
    nvm alias default "$NODE_VERSION" || true
    echo "✅ Node $NODE_VERSION 已安装并设为默认版本"
else
    echo "ℹ️ 未检测到 Node 离线包，可稍后放置 node-vX.Y.Z-linux-x64.tar.xz 后重新运行本脚本安装"
fi

echo "=============================================="
echo "✅ NVM 离线安装完成"
echo "👉 执行: source ~/.bashrc"
echo "👉 验证: nvm -v && node -v && npm -v"
echo "=============================================="
