#!/bin/bash

# Usage: sudo ./bramble_rmm_install.sh <ENROLLMENT_KEY>

set -e

ENROLLMENT_KEY="$1"

if [ -z "$ENROLLMENT_KEY" ]; then
  echo "Enrollment key not provided."
  exit 1
fi

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

echo "Creating directories..."
sudo mkdir -p "$TEMP_DIR"
sudo mkdir -p "$INSTALL_DIR/temp"
cd "$TEMP_DIR"

# Detect OS and install dependencies
install_dependencies() {
  echo "Installing required packages..."

  if [ -f /etc/debian_version ]; then
    sudo apt-get update
    sudo apt-get install -y curl jq unzip

    if ! command -v node &> /dev/null || [ "$(node -v | cut -d. -f1 | tr -d v)" -lt "$NODE_MIN_VERSION" ]; then
      curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
      sudo apt-get install -y nodejs
    fi

  elif [ -f /etc/redhat-release ]; then
    sudo dnf install -y curl jq unzip

    if ! command -v node &> /dev/null || [ "$(node -v | cut -d. -f1 | tr -d v)" -lt "$NODE_MIN_VERSION" ]; then
      curl -fsSL https://rpm.nodesource.com/setup_22.x | sudo bash -
      sudo dnf install -y nodejs
    fi

  else
    echo "Unsupported OS. Please install dependencies manually."
    exit 1
  fi
}

install_dependencies

# Ensure Node is now installed
if ! command -v node &> /dev/null || ! command -v npm &> /dev/null; then
  echo "Node.js or npm installation failed. Exiting."
  exit 1
fi

# Download latest agent
echo "Downloading Bramble RMM agent..."
AGENT_VERSION=$(curl -s https://api.cloud.brambleit.com/v1/app/rmm/version/agent/linux | jq -r .latest)
AGENT_ZIP="Base_Client_v$AGENT_VERSION.zip"
curl -o "$TEMP_DIR/$AGENT_ZIP" "https://download.cloud.brambleit.com/rmm/agent/linux/$AGENT_ZIP"

echo "Replacing agent files..."

echo "Extracting new version of Bramble RMM..."
# Extract new version directly into the install dir
sudo unzip -o "$TEMP_DIR/$AGENT_ZIP" -d "$INSTALL_DIR"
echo "Moving new version of Bramble RMM..."
sudo cp -r "$INSTALL_DIR/build/"* "$INSTALL_DIR/"
echo "Cleaning up build folder..."
sudo rm -rf "$INSTALL_DIR/build"

echo "Installing packages..."
cd "$INSTALL_DIR"
npm install

# Make all .sh files executable
echo "Making .sh files executable..."
find "$INSTALL_DIR" -type f -name "*.sh" -exec sudo chmod +x {} \;

echo "Setting folder permissions..."
sudo chown -R root:root "$INSTALL_DIR"
sudo chmod -R 755 "$INSTALL_DIR"

# Ensure config.json is writable if it exists
CONFIG_FILE="$INSTALL_DIR/config.json"

if [ -f "$CONFIG_FILE" ]; then
  echo "Setting permissions on config.json..."
  sudo chmod 644 "$CONFIG_FILE"
else
  echo "Creating config.json..."
  sudo tee "$CONFIG_FILE" > /dev/null <<EOF
{
  "RMM_Enrolled": false,
  "RMM_ServerURL": "https://api.cloud.brambleit.com",
  "RMM_EnrollmentKey": "$ENROLLMENT_KEY"
}
EOF
  sudo chmod 644 "$CONFIG_FILE"
fi


# Preserve the config file
echo "Config file already exists. Skipping config.json overwrite..."

# Create systemd service file if not exists
SERVICE_FILE="/etc/systemd/system/bramble-rmm-agent.service"
if [ ! -f "$SERVICE_FILE" ]; then
  echo "Creating systemd service..."

  sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=Bramble RMM Agent
After=network.target

[Service]
ExecStart=$(which node) $INSTALL_DIR/index.js
WorkingDirectory=$INSTALL_DIR
Restart=always
Environment=NODE_ENV=production
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=bramble-rmm-agent
User=root
Group=root

[Install]
WantedBy=multi-user.target
EOF
fi

# Enable and start service
echo "Enabling and starting the service..."
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable bramble-rmm-agent
sudo systemctl start bramble-rmm-agent

echo "Bramble RMM agent installed and running."
