#!/bin/bash
#
#  MCU Node Repository Update Tool v1.0.4
#  Created by Enrico Buttignol (ebuttignol@radiantcooling.com) on Sep 9, 2021
#  Copyright by Messana Hydronic Technologies
#
#  Changelog:
#
#  Mmm dd, yyyy - Name Surname (email@server.com) - description
#
#  Feb 12, 2021 - Massimiliano Bortolus (marx86@gmail.com - Added Redis password
#  Sep 16, 2022 - Enrico Buttignol (enrico.buttignol@gmail.com) - Added header and Redis password variables
#  Sep 21, 2022 - Massimiliano Bortolus (mbortolus@radiantcooling.com) - Tested and fixed - added existence file check before deletion
#  Dec 2, 2022 - Enrico Buttignol (ebuttignol@radiantcooling.com) - Updated bash colors and code optimization
#  Jul 5, 2024 - Sevan Soukiassian (ssoukiassian@messana.tech) - Updated from Node.js v12 to Node.js v20, and removed the duplicated "mht-node-repository.sh" version with the extension
#
#  sudo ./mht-node-repository-update

# Variable definitions
# Colors
COLOR_SECTION='\033[0;36m'
COLOR_INFO='\033[0;96m'
COLOR_EXECUTED='\033[0;32m'
COLOR_WARNING='\033[33m'
COLOR_ERR='\033[0;31m'
NOCOLOR='\033[0m'

# Values
REDISKEY=$(awk '/^requirepass /{print $2}' /etc/redis/redis.conf | uniq)
NODE_VERSION=$(node -v)
REDIS_VERSION=$(redis-server -v | grep -Po '(?<=Redis server v=)([\d]*.[\d]*.[\d]*)' | awk -F'[^0-9]+' '{ print $1 }')
OLD_REDIS_VERSION=3
if [ "$REDIS_VERSION" -gt "$OLD_REDIS_VERSION" ]; then
    REDIS_WARNING_PASSWORD="--no-auth-warning"
else
    REDIS_WARNING_PASSWORD=""
fi

printf "\n"
printf "%s""${COLOR_SECTION}[»»»] NODE REPOSITORY UPDATE STARTED [«««]${NOCOLOR}"
printf "\n"

sed -i 's/12/20/g' /etc/apt/sources.list.d/nodesource.list
apt update -y
apt install nodejs

if [ -f /etc/cron.daily/mht-node-repository-update  ]; then
	shred -u /etc/cron.daily/mht-node-repository-update
fi

echo "SET RTT_MCU_000_SWVersionN \"$NODE_VERSION\"" | redis-cli -a "$REDISKEY" REDIS_WARNING_PASSWORD >> /dev/null 2>&1
echo "HSET RTT_MCU_ATT_SWVersionN DescUS \"Node software version\"" | redis-cli -a "$REDISKEY" REDIS_WARNING_PASSWORD >> /dev/null 2>&1
echo "HSET RTT_MCU_ATT_SWVersionN Name \"SWVersionN\"" | redis-cli -a "$REDISKEY" REDIS_WARNING_PASSWORD >> /dev/null 2>&1
echo "HSET RTT_MCU_ATT_SWVersionN Type \"6\"" | redis-cli -a "$REDISKEY" REDIS_WARNING_PASSWORD >> /dev/null 2>&1

# MHT services restart
/bin/systemctl restart messana
/bin/systemctl restart homebridge

printf "%s""${COLOR_SECTION}[»»»] NODE REPOSITORY UPDATE COMPLETED [«««]${NOCOLOR}\n"
printf "\n"
printf "\n"

exit 0
