#!/bin/bash
# ======================================================================
#
# NVM INIT
#
# This is a helper tool for build processes with nodejs.
# It installs nvm and offers a method to remove nvm again.
#
# ----------------------------------------------------------------------
# 2019-06-18  first lines  <axel.hahn@iml.unibe.ch>
# ======================================================================

# ----------------------------------------------------------------------
# CONFIG
# ----------------------------------------------------------------------
NVM_REPO=https://github.com/nvm-sh/nvm.git


# ----------------------------------------------------------------------
# FUNCTIONS
# ----------------------------------------------------------------------
function nvmremove(){
    echo "REMOVE NVM ..."

    if [ -z $NVM_DIR ]; then
        echo ERROR: sorry, NVM_DIR is empty.
        exit 1
    fi

    echo -n "Removing NVM from build directory: [$NVM_DIR] ..."
    rm -rf "$NVM_DIR" || exit 3
    echo OK

    echo -n "unload ... "
    nvm unload || exit 2
    echo OK
}

# ----------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------

echo
echo ===== NVM INIT =====
echo 

if [ -z $DIR_APPROOT ]; then
    echo ERROR: this script runs in a onbuilt process only.
    echo Currently here is no DIR_APPROOT to define a temporary working dir.
    exit 1
fi

# INSTALL NVM ... see
# https://github.com/nvm-sh/nvm#manual-install
export NVM_DIR="$DIR_APPROOT/.nvm" && (
  git clone $NVM_REPO "$NVM_DIR"
  cd "$NVM_DIR"
  git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)`
) && . "$NVM_DIR/nvm.sh" || exit 1
