#!/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=~/.zshrc
# global_config_file=~/.bash_profile
global_config_file=~/.profile


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)

echo "node_version $node_version npm_version $npm_version"

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

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

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

if [[ $npm_version != $npm_recommented_version* ]];
  then
    echo "npm i -g npm@$npm_recommented_version"
    npm i -g npm@$npm_recommented_version
    echo "npm $(npm -v) ${GREEN}Updated${NC}"
  else
    echo "npm $(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
    echo "$npm_package_scpoe:registry registry ${GREEN}Updated${NC}"
    npm config set $npm_package_scpoe:registry="$local_registry"
  else
    echo "$npm_package_scpoe registry url ${GREEN}Correct${NC}"
  fi
}

updateLocalRegistry "@zoho"
updateLocalRegistry "@zohocharts"

if [[ $node_version = '' ]] || [[ $node_version != v$node_recommented_version* ]]
  then
    echo "please install or switch to nodejs $node_recommented_version"
    echo "Node Official Site https://nodejs.org/en/download/releases/"
  else
    echo "node version $node_version ${GREEN}Correct${NC}"
fi

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