#!/bin/bash

source /opt/scripts_local/shared_functions.sh

echo "Installing Nodejs"

NODE_VER=$(cut -c 2-10 <<< "$(node -v)")
if compare_version "$NODE_VER" "18.0.0" ; then
  echo "Node already installed, skipping."
else 
  echo "Node not found or wrong version on system, installing ..."
  sudo apt-get remove nodejs -y
  sudo apt-get purge nodejs -y
  sudo apt-get remove npm -y
  sudo apt-get autoremove -y
  sudo rm -rf /etc/apt/keyrings/nodesource.gpg
  sudo rm -rf /etc/apt/sources.list.d/nodesource.list
  sudo rm /usr/bin/node >/dev/null 2>&1
  sudo rm -rf /opt/local/bin/node
  sudo rm -rf /usr/local/bin/node*
  sudo rm -rf /usr/local/bin/node-waf 
  sudo rm -rf /usr/local/bin/npm
  sudo rm -rf /opt/local/include/node
  sudo rm -rf /usr/local/include/node*
  sudo rm -rf /usr/local/lib/dtrace/node.d 
  sudo rm -rf /opt/local/lib/node_modules
  sudo rm -rf /usr/local/lib/node 
  sudo rm -rf /usr/local/lib/node*
  sudo rm -rf /usr/local/lib/pkgconfig/nodejs.pc 
  sudo rm -rf /usr/local/share/man/man1/node* 
  sudo rm -rf /usr/local/share/man/man1/node.1
  sudo rm -rf ~/.npm 
  sudo rm -rf ~/.node-gyp 
  sudo npm rm npm -g
  NODE_MAJOR=18
  sudo apt-get update
  sudo apt-get install -y 
  # sudo apt-get install -y ca-certificates curl gnupg
  sudo mkdir -p /etc/apt/keyrings
  curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
  echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
  sudo apt-get update
  sudo apt-get install nodejs -y
  sudo apt-get install npm -y
  echo "Finished Installing Nodejs"
fi