#!/usr/bin/env bash

function raise_err() {
  local msg=$1
  echo -e "$msg" >&2
  exit 1
}

# nvm 이 로드되어 있는지 확인
if ! command -v nvm >/dev/null 2>&1; then
  # nvm.sh 가 존재한다면 불러오기
  if [ -s "$NVM_DIR/nvm.sh" ]; then
    # shellcheck disable=SC1090
    source "$NVM_DIR/nvm.sh"
  elif [ -s "$HOME/.nvm/nvm.sh" ]; then
    # shellcheck disable=SC1090
    source "$HOME/.nvm/nvm.sh"
  else
    raise_err "nvm is not installed or not sourced. See https://github.com/nvm-sh/nvm"
  fi
fi

# nvm -version 실행
echo "=== Running nvm test ==="
if ! nvm_version > /dev/null; then
  echo "⚠️ nvm doctor reported issues. Please review above output."
fi

# npm 이 있는지 확인
if ! command -v npm >/dev/null 2>&1; then
  raise_err "npm is not available. Install through nvm. See https://nodejs.org/en/download for reference"
fi

# npm doctor 실행 (출력 파싱용)
DOCTOR_OUTPUT=$(npm doctor || true)

echo $DOCTOR_OUTPUT

# set -e 는 여기부터 적용 (npm doctor 가 실패하더라도 스크립트는 계속 진행해야 하므로 위에서는 true 처리)
set -e

REQUIRED_NODE=$(echo "$DOCTOR_OUTPUT" | grep "Use node v" | sed -E 's/.*Use node v([0-9]+\.[0-9]+\.[0-9]+).*/\1/')
REQUIRED_NPM=$(echo "$DOCTOR_OUTPUT" | grep "Use npm v"   | sed -E 's/.*Use npm v([0-9]+\.[0-9]+\.[0-9]+).*/\1/')

CURRENT_NODE=$(node -v 2>/dev/null | sed 's/v//')
CURRENT_NPM=$(npm -v 2>/dev/null)

echo "=== npm doctor suggested versions ==="
echo "Required Node.js: ${REQUIRED_NODE:-N/A}"
echo "Required npm:     ${REQUIRED_NPM:-N/A}"

echo "=== Current versions ==="
echo "Node.js: ${CURRENT_NODE:-N/A}"
echo "npm:     ${CURRENT_NPM:-N/A}"

# Node.js 업데이트
if [ -n "$REQUIRED_NODE" ] && [ "$CURRENT_NODE" != "$REQUIRED_NODE" ]; then
  echo ">>> Installing Node.js $REQUIRED_NODE via nvm"
  nvm install "$REQUIRED_NODE"
  nvm alias default "$REQUIRED_NODE"
  nvm use default
else
  echo "Node.js version is already up-to-date."
fi

# npm 업데이트
if [ -n "$REQUIRED_NPM" ] && [ "$CURRENT_NPM" != "$REQUIRED_NPM" ]; then
  echo ">>> Installing npm $REQUIRED_NPM"
  npm install -g "npm@$REQUIRED_NPM"
else
  echo "npm version is already up-to-date."
fi

echo "=== Final versions ==="
node -v
npm -v
