#!/bin/bash
#
#  MHT MCU Upgrade Script v1.1.0
#  Created by Enrico Buttignol (ebuttignol@messana.tech) on Jan 31, 2024
#  Copyright by Messana Hydronic Technologies
#
#  Changelog:
#
#  Mmm dd, yyyy - Name Surname (email@server.com) - description
#
#  Aug 1, 2024 - Enrico Buttignol (ebuttignol@radiantcooling.com) - Added remote update cron string check and modify condition
#
#  sudo ./upgrade

export DEBIAN_FRONTEND=noninteractive

# 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
CRONTABFILE='/etc/crontab'
DISABLEDREMOTEUPDATECRON='#* * * * * root /etc/cron.daily/upgrade &>/dev/null' # This is the commented portal remote update cron string.
REMOTEUPDATECRON='* * * * * root /etc/cron.daily/upgrade &>/dev/null' # This is the uncommented portal remote update cron string.
VPN_DIRECTORY="/etc/openvpn/" # Directory containing the files

# Variable to store the valid file name
CODE=""

# Find .conf files in the directory, excluding 9999-999.conf
for file in ${VPN_DIRECTORY}*.conf; do
  # Skip the file if it's 9999-999.conf
  if [[ "$(basename "$file")" == "9999-999.conf" ]]; then
    continue
  fi

  # Extract the filename without the path and without the extension
  filename=$(basename "$file" .conf)

  # Assign the filename to the variable
  CODE="$filename"

  # Break after the first valid file is found
  break
done

# Backup the current crontab file
sudo cp "$CRONTABFILE" "${CRONTABFILE}.bak"

# Remote upgrade cron check and modify using awk
awk -v enabled="$REMOTEUPDATECRON" -v disabled="$DISABLEDREMOTEUPDATECRON" '
BEGIN { found_enabled=0; found_disabled=0; }
{
    if ($0 == enabled) {
        found_enabled = 1;
        $0 = disabled;
    }
    if ($0 == disabled) {
        found_disabled = 1;
    }
    lines[NR] = $0;
}
END {
    if (found_enabled && !found_disabled) {
        # Already commented, do nothing
        for (i = 1; i <= NR; i++) {
            print lines[i];
        }
    } else if (!found_enabled && !found_disabled) {
        # Neither line exists, add the disabled line as the penultimate line
        for (i = 1; i <= NR - 1; i++) {
            print lines[i];
        }
        print disabled;
        print lines[NR];
    } else {
        # Either the enabled line was found and commented or it'"'"'s already commented
        for (i = 1; i <= NR; i++) {
            print lines[i];
        }
    }
}' "$CRONTABFILE" | sudo tee "$CRONTABFILE" > /dev/null

# Restart cron service to apply changes
sudo systemctl restart cron
if [ $? -eq 0 ]; then
   printf "%s""${COLOR_EXECUTED}[+]${NOCOLOR} The cron service has been restarted successfully.\n"
else
   printf "%s""${COLOR_ERR}[×]${NOCOLOR} Failed to restart the cron service.\n"
fi

# Update apt packages
apt update -y >/dev/null 2>&1

# Upgrade MHT packages and clean system
apt install --only-upgrade messana-frontend -y >/dev/null 2>&1
apt install --only-upgrade messana-logic -y >/dev/null 2>&1
apt autoclean >/dev/null 2>&1

printf "\n"
printf "%s""${COLOR_SECTION}[»»»] MHT HOMEBRIDGE PLUGINS UPDATE STARTED [«««]${NOCOLOR}"
printf "\n"

# Function to update npm to the desired version
update_npm() {
    local desired_version="10.8.2"
    local current_version=$(npm -v)

    if [ "$current_version" != "$desired_version" ]; then
        printf "%s""${COLOR_EXECUTED}[+]${NOCOLOR} Updating npm from $current_version to $desired_version.\n"
        npm install -g npm@$desired_version >/dev/null 2>&1
    else
        printf "%s""${COLOR_INFO}[i]${NOCOLOR} npm is already at the desired version ($current_version).\n"
    fi
}

# Update npm to the desired version
update_npm

# Check and install MHT npm packages
check_and_update_npm_package() {
    local package_name="$1"
    local current_version=$(npm list -g --depth 1 --parseable=true --long "$package_name" | grep -oP '\d+\.\d+\.\d+')
    local latest_version=$(npm show "$package_name" version)

    if [ "$current_version" != "$latest_version" ]; then
        printf "%s""${COLOR_EXECUTED}[+]${NOCOLOR} Updating $package_name from $current_version to $latest_version.\n"
        npm install -g "$package_name@latest" >/dev/null 2>&1
        need_restart=1
    else
        printf "%s""${COLOR_INFO}[i]${NOCOLOR} The plugin $package_name is already updated. Version: $current_version\n"
    fi
}

# Check and install MHT npm packages
need_restart=0
check_and_update_npm_package "homebridge-messana-zone"
check_and_update_npm_package "homebridge-messana-macrozone"
check_and_update_npm_package "homebridge-messana-system"
check_and_update_npm_package "homebridge-messana-fancoil"
check_and_update_npm_package "homebridge-messana-changeover"

# Restart Homebridge if updates were installed
if [ $need_restart -eq 1 ]; then
    service homebridge restart >/dev/null
    printf "%s""${COLOR_EXECUTED}[+]${NOCOLOR} Homebridge restarted after npm package updates.\n"
else
    printf "%s""${COLOR_INFO}[i]${NOCOLOR} No updates for npm packages. Skipping Homebridge restart.\n"
fi

printf "%s""${COLOR_SECTION}[»»»] MHT HOMEBRIDGE PLUGINS UPDATE COMPLETED [«««]${NOCOLOR}\n"
printf "\n"
printf "\n"

# Run hardware details update script
/usr/share/messana/scripts/mht-hw-details-update.sh

# Send status update to the server
curl -s -X POST https://service.radiantcooling.com/portal/api/status/upgrade-status \
    -H "Content-Type: application/json" \
    -d '{"mcuCode": "'"${CODE}"'", "status": "idle"}' > /dev/null

exit 0
