#!/bin/bash

set -e

# === Check for root privileges ===
if [[ "$EUID" -ne 0 ]]; then
  echo "❌ Please run this script as root (e.g., using sudo)"
  exit 1
fi

echo "==============================================="
echo "   🔐 SoftShield Agent Universal Installer     "
echo "   Supports most Linux   (systemd-based)       "
echo "==============================================="

# === Prompt for Agent Group ===
read -p "Enter the Agent Group name: " AGENT_GROUP
if [[ -z "$AGENT_GROUP" ]]; then
  echo "❌ Group name cannot be empty"
  exit 1
fi

MANAGER_HOST="softshield.softsquaregroup.com"

# === Detect OS ===
source /etc/os-release
OS_ID=${ID,,}
OS_LIKE=${ID_LIKE,,}
echo ""
echo "🔍 Detected OS: $OS_ID ($OS_LIKE)"

# === Ensure curl is installed ===
if ! command -v curl >/dev/null 2>&1; then
  echo "📦 Installing curl..."
  if command -v apt >/dev/null; then
    apt update && apt install -y curl
  elif command -v dnf >/dev/null; then
    dnf install -y curl
  elif command -v yum >/dev/null; then
    yum install -y curl
  elif command -v zypper >/dev/null; then
    zypper install -y curl
  elif command -v apk >/dev/null; then
    apk add --no-cache curl
  else
    echo "❌ Cannot install curl: unknown package manager"
    exit 1
  fi
fi

# === Download & Install Wazuh Agent ===
case "$OS_ID" in
  ubuntu|debian|linuxmint)
    echo "📦 Installing on Debian-based system..."
    FILE="wazuh-agent_4.11.0-1_amd64.deb"
    URL="https://packages.wazuh.com/4.x/apt/pool/main/w/wazuh-agent/$FILE"
    curl -Lo "$FILE" "$URL"
    WAZUH_MANAGER="$MANAGER_HOST" \
    WAZUH_AGENT_GROUP="$AGENT_GROUP" \
    dpkg -i "$FILE" || apt install -f -y
    rm -f "$FILE"
    ;;

  centos|rhel|rocky|almalinux|fedora|amzn|ol)
    echo "📦 Installing on RPM-based system (e.g. CentOS, RHEL, Oracle Linux)..."
    FILE="wazuh-agent-4.11.0-1.x86_64.rpm"
    URL="https://packages.wazuh.com/4.x/yum/$FILE"
    curl -Lo "$FILE" "$URL"
    WAZUH_MANAGER="$MANAGER_HOST" \
    WAZUH_AGENT_GROUP="$AGENT_GROUP" \
    rpm -ihv "$FILE"
    rm -f "$FILE"
    ;;

  opensuse*|sles)
    echo "📦 Installing on openSUSE/SLES..."
    FILE="wazuh-agent-4.11.0-1.x86_64.rpm"
    URL="https://packages.wazuh.com/4.x/yum/$FILE"
    curl -Lo "$FILE" "$URL"
    zypper --non-interactive install "$FILE"
    rm -f "$FILE"
    ;;

  alpine)
    echo "⚠️ Alpine Linux detected. Not officially supported by Wazuh Agent."
    echo "You may consider running the agent in Docker or use another OS."
    exit 1
    ;;

  *)
    echo "❌ Unsupported or untested OS: $OS_ID"
    exit 1
    ;;
esac

# === Start and enable Wazuh Agent ===
echo ""
echo "🚀 Starting SoftShield Agent..."
systemctl daemon-reexec
systemctl enable wazuh-agent
systemctl start wazuh-agent
systemctl status wazuh-agent --no-pager || echo "⚠️ Agent started, but status check failed."

# === Summary ===
echo ""
echo "✅ SoftShield Agent installation completed!"
echo "🎯 Group: $AGENT_GROUP"
echo "🌐 Manager: $MANAGER_HOST"

