#!/usr/bin/env bash
#
# Create Wazuh 5.0 agent groups before any agent enrols.
# Groups must exist on the manager first: an agent that declares a group in
# <enrollment><groups> which does not exist has its enrolment rejected.
#
# Two equivalent routes are shown. Pick one.
#
# Reference:
#   https://documentation.wazuh.com/5.0-beta/user-manual/agent/agent-management/grouping-agents.html
#   https://github.com/wazuh/wazuh/blob/main/docs/guide/migration/agent-groups-migration.md

set -euo pipefail

GROUPS=("linux-servers" "windows" "databases" "dmz")

# ---------------------------------------------------------------------------
# Route 1: the agent_groups tool, run locally on the manager as root.
# ---------------------------------------------------------------------------
create_with_cli() {
  for g in "${GROUPS[@]}"; do
    /var/wazuh-manager/bin/agent_groups -a -g "${g}" -q
  done
  /var/wazuh-manager/bin/agent_groups -l
}

# ---------------------------------------------------------------------------
# Route 2: the manager API on port 55000. Use this from configuration management.
# ---------------------------------------------------------------------------
: "${WAZUH_MANAGER:?set WAZUH_MANAGER to the manager address}"
: "${WAZUH_API_USER:?set WAZUH_API_USER}"
: "${WAZUH_API_PASSWORD:?set WAZUH_API_PASSWORD}"

create_with_api() {
  local token
  token=$(curl -sk -u "${WAZUH_API_USER}:${WAZUH_API_PASSWORD}" -X POST \
    "https://${WAZUH_MANAGER}:55000/security/user/authenticate?raw=true")

  for g in "${GROUPS[@]}"; do
    curl -sk -X POST "https://${WAZUH_MANAGER}:55000/groups" \
      -H "Authorization: Bearer ${token}" \
      -H "Content-Type: application/json" \
      -d "{\"group_id\": \"${g}\"}"
    echo
  done
}

case "${1:-cli}" in
  cli) create_with_cli ;;
  api) create_with_api ;;
  *)   echo "usage: $0 [cli|api]" >&2; exit 2 ;;
esac
