#!/usr/bin/env bash
#
# Back up the Wazuh 5.0 MANAGER configuration and agent identities.
#
# IMPORTANT: the Wazuh 5.0 beta documentation has NO manager files-backup
# page; that section is absent from the beta tree. The paths below are the
# 5.0 manager paths documented elsewhere in the beta (wazuh-manager.conf,
# authd.pass, the shared group directory), assembled into a backup script.
# Re-check against the official procedure at GA.
#
# This does NOT back up detection content. Rules, decoders, integrations,
# KVDBs, filters and spaces live in the Wazuh indexer under the content
# manager, in the wazuh-threatintel-* indices. Export those through the
# indexer content manager API and keep them in version control.
#
# Run as root on the manager node.

set -euo pipefail

if [[ $EUID -ne 0 ]]; then
  echo "Run as root." >&2
  exit 1
fi

WAZUH_HOME=/var/wazuh-manager
bkp_folder=~/wazuh_manager_backup/$(date +%F_%H:%M)
mkdir -p "$bkp_folder"
echo "$bkp_folder"

cat /etc/*release* > "$bkp_folder/host-info.txt"
echo -e "\n$(hostname): $(hostname -I)" >> "$bkp_folder/host-info.txt"
"$WAZUH_HOME/bin/wazuh-control" info >> "$bkp_folder/host-info.txt" 2>&1 || true

rsync -aREz \
  "$WAZUH_HOME/etc/wazuh-manager.conf" \
  "$WAZUH_HOME/etc/client.keys" \
  "$WAZUH_HOME/etc/authd.pass" \
  "$WAZUH_HOME/etc/shared/" \
  "$bkp_folder"

# merged.mg is regenerated by the manager; the migration documentation
# excludes it explicitly. Drop it from the copy.
find "$bkp_folder" -name 'merged.mg' -delete

# Certificates: whatever your installation issued. Adjust the path.
# rsync -aREz "$WAZUH_HOME/etc/certs/" "$bkp_folder"   # TODO: confirm path

tar -cvzf wazuh-manager-backup.tar.gz "$bkp_folder"

echo
echo "Done: wazuh-manager-backup.tar.gz"
echo
echo "Reminder: client.keys is the agent identity store. Losing it means"
echo "re-enrolling every agent. authd.pass is a live credential. Treat this"
echo "archive as a secret."
