#!/bin/bash

node_recommented_version="16"
npm_recommented_version="6"
local_registry="http://cm-npmregistry.csez.zohocorpin.com"
dollor_symbol='$'
global_p=~/npm-global
global_config_file=~/.bashrc


GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color


node_version=$(node -v)
npm_prefix=$(npm config get prefix)
npm_version=$(npm -v)

printf "\nnode_version $node_version npm_version $npm_version"

if [[ $node_version = '' ]] || [[ $node_version != v$node_recommented_version* ]]
  then
    curl -sL https://deb.nodesource.com/setup_${node_recommented_version}.x| sudo -E bash -
    printf "\nnodejs $node_recommented_version and $(node -v) ${GREEN}Installed${NC}"
  else
    printf "\nnode version $node_version ${GREEN}Correct${NC}"
fi

if [[ "$npm_prefix" = "/usr/local" ]]
  then
    printf "\nnpm_prefix $npm_prefix"
    [[ -d "$global_p" ]] && printf "\nDirectory $global_p exists."
    [[ ! -d "$global_p" ]] && mkdir $global_p
    npm config set prefix="$global_p"
    printf "\nnpm_prefix ${GREEN}Updated${NC}"
  else
    printf "\nnpm_prefix ${GREEN}Correct${NC}"
fi

if [[ "$PATH" != *"$global_p/bin:"* ]] && [[ "$PATH" != "$global_p/bin:"* ]] 
  then
    # write in global config file
    sudo printf "\nexport PATH=$global_p/bin:${dollor_symbol}PATH" >> $global_config_file
    printf "\n${dollor_symbol}PATH variable ${GREEN}Updated${NC}"
  else
    printf "\n${dollor_symbol}PATH variable ${GREEN}Correct${NC}"
fi

if [[ "$NODE_OPTIONS" != "--max-old-space-size=14096" ]]
  then
    sudo printf "\nexport NODE_OPTIONS=--max-old-space-size=14096" >> $global_config_file
    printf "\n${dollor_symbol}NODE_OPTIONS variable ${GREEN}Updated${NC}"
  else
    printf "\n${dollor_symbol}NODE_OPTIONS variable ${GREEN}Correct${NC}"
fi

if [[ $npm_version != $npm_recommented_version* ]];
  then
    printf "\nnpm i -g npm@$npm_recommented_version"
    npm i -g npm@$npm_recommented_version
    printf "\nnpm $(npm -v) ${GREEN}Updated${NC}"
  else
    printf "\nnpm $(npm -v) version ${GREEN}Correct${NC}"
fi

updateLocalRegistry() {
  npm_package_scpoe="$1"
  npm_current_registry=$(npm config get $npm_package_scpoe:registry)

  if [[ "$npm_current_registry" != "$local_registry" ]]
  then
    printf "\n$npm_package_scpoe:registry registry ${GREEN}Updated${NC}"
    npm config set $npm_package_scpoe:registry="$local_registry"
  else
    printf "\n$npm_package_scpoe registry url ${GREEN}Correct${NC}"
  fi
}

updateLocalRegistry "@zoho"
updateLocalRegistry "@zohocharts"

printf "\nPlease open new terminal and check ${CYAN}echo ${dollor_symbol}PATH${NC} starts with ${CYAN}$global_p/bin${NC}"
printf "\nTo work with current terminal Please run ${CYAN}source $global_config_file${NC}\n"
