#!/bin/bash

# Update Bramble RMM Agent on Linux
set -e

INSTALL_DIR="/opt/bramble-rmm"
TEMP_DIR="$INSTALL_DIR/temp"
NODE_MIN_VERSION="22"
SERVICE_NAME="bramble-rmm-agent"

# Optional 1st script arg: override RMM_ServerURL in the existing
# config.json (e.g. testing the brambleit.cloud vanity-domain migration on
# one device). Leave blank/omit to update the agent code only, exactly as
# before — this is purely opt-in and does not affect any existing usage of
# this script.
SERVER_URL="$1"

echo "Ensuring directories exist..."
mkdir -p "$TEMP_DIR"

install_dependencies() {
  echo "Ensuring required packages are installed..."

  if [ -f /etc/debian_version ]; then
    echo "Debian-based system detected."

    echo "Updating apt-get..."
    if ! apt-get update; then
      echo "apt-get update failed. Checking for dpkg lock issue..." >&2
      dpkg --configure -a
      if ! apt-get update; then
        echo "Failed to recover from dpkg error during update."
        exit 1
      fi
    fi

    echo "Installing curl, jq, unzip..."
    if ! apt-get install -y curl jq unzip; then
      echo "apt-get install failed. Trying to fix dpkg..." >&2
      dpkg --configure -a
      if ! apt-get install -y curl jq unzip; then
        echo "Failed to recover from dpkg error during install."
        exit 1
      fi
    fi

  elif [ -f /etc/redhat-release ]; then
    echo "Red Hat-based system detected."
    dnf install -y curl jq unzip
  else
    echo "Unsupported OS. Please install dependencies manually."
    exit 1
  fi
}

install_dependencies

if ! command -v node &> /dev/null || [ "$(node -v | cut -d. -f1 | tr -d v)" -lt "$NODE_MIN_VERSION" ]; then
  echo "Node.js v$NODE_MIN_VERSION or higher is required. Please update Node.js."
  exit 1
fi

echo "Fetching latest Bramble RMM version info..."
# PILOT: pinned to an unpublished build (not in bramble_rmm.master).
AGENT_VERSION="6.22.0"
EXPECTED_SHA256="80ea7656e6054233d22a648811004abe57016f55fff66932ee51e3b0d79032b8"

AGENT_ZIP="Base_Client_v$AGENT_VERSION.zip"
ZIP_PATH="$TEMP_DIR/$AGENT_ZIP"

echo "Downloading Bramble RMM agent v$AGENT_VERSION..."
curl -fsSL -o "$ZIP_PATH" "https://download.cloud.brambleit.com/rmm/agent/linux/$AGENT_ZIP"

echo "Verifying checksum..."
ACTUAL_SHA256=$(sha256sum "$ZIP_PATH" | awk '{print $1}')
if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then
  echo "Checksum mismatch for $AGENT_ZIP: expected $EXPECTED_SHA256, got $ACTUAL_SHA256. Aborting update." >&2
  rm -f "$ZIP_PATH"
  exit 1
fi
echo "Checksum verified."

echo "Extracting new version..."
unzip -o "$ZIP_PATH" -d "$INSTALL_DIR"

echo "Updating agent files..."
cp -r "$INSTALL_DIR/build/"* "$INSTALL_DIR/"
rm -rf "$INSTALL_DIR/build"

echo "Installing dependencies..."
cd "$INSTALL_DIR"
if [ -f package-lock.json ]; then
  npm ci --omit=dev
else
  npm install --omit=dev
fi

echo "Ensuring .sh files are executable..."
find "$INSTALL_DIR" -type f -name "*.sh" -exec chmod +x {} \;

rm -f "$ZIP_PATH"

CONFIG_FILE="$INSTALL_DIR/config.json"
if [ -n "$SERVER_URL" ] && [ -f "$CONFIG_FILE" ]; then
  echo "Updating RMM_ServerURL to $SERVER_URL..."
  UPDATED_CONFIG=$(jq --arg url "$SERVER_URL" '.RMM_ServerURL = $url' "$CONFIG_FILE")
  echo "$UPDATED_CONFIG" > "$CONFIG_FILE"
fi

echo "Bramble RMM agent updated to version $AGENT_VERSION."
# This script runs as a child of the very service it's restarting, in the
# same systemd cgroup — a synchronous restart here would kill this process
# (and the result-reporting that follows it) before it finishes. Backgrounding
# with a short delay lets the script exit and its result get reported first;
# the restart request reaches systemd regardless of what happens to this
# process afterward.
(sleep 2; systemctl restart "$SERVICE_NAME") >/dev/null 2>&1 &
echo "Restart scheduled."

