#!/usr/bin/env bash
# 安装 Node.js
#
# 用 NodeSource 官方源装指定主版本（默认 22 LTS）。
# 已经装过会先问一句 —— 问句从 /dev/tty 读，curl | bash 下不会把脚本自身当答案。
# 用法：bash nodejs-install.sh [主版本]      例：bash nodejs-install.sh 20

set -e

# 需要 root：下面的系统级改动都直接执行，不再逐条 sudo
if [ "$(id -u)" -ne 0 ]; then
    echo '[!] 这个脚本需要 root 权限，请用 sudo 重新运行：'
    echo '    curl -fsSL 脚本地址 | sudo bash'
    echo '    或已经下载到本地：sudo bash 本文件'
    exit 1
fi

MAJOR=22
if [ "$#" -ge 1 ]; then
    MAJOR="$1"
fi

case "$MAJOR" in
    ''|*[!0-9]*) echo "[!] 主版本要是数字，收到：$MAJOR"; exit 1 ;;
esac

echo "====== 安装 Node.js $MAJOR ======"

if command -v node >/dev/null 2>&1; then
    echo "[!] 已经装过：$(node -v)"
    answer=N
    if [ -r /dev/tty ]; then
        read -rp '是否重新安装？(y/N): ' answer < /dev/tty || answer=N
    fi
    case "$answer" in
        y|Y) ;;
        *) echo '[*] 已跳过'; exit 0 ;;
    esac
fi

if ! command -v curl >/dev/null 2>&1; then
    apt-get update -qq
    apt-get install -y curl
fi

echo '[*] 添加 NodeSource 源...'
curl -fsSL "https://deb.nodesource.com/setup_$MAJOR.x" | bash -

echo '[*] 安装 nodejs...'
apt-get install -y nodejs

echo ''
echo '====== 完成 ======'
echo "  node：$(node -v)"
echo "  npm：$(npm -v)"
