#!/usr/bin/env bash
#
# Back up the Wazuh 5.0 indexer CONFIGURATION on one node.
#
# Commands and paths are taken verbatim from:
# https://documentation.wazuh.com/5.0-beta/user-manual/wazuh-indexer/backup-and-restore.html
#
# This backs up configuration only. It does NOT back up indexed data.
# For data, register a snapshot repository and take a snapshot. See the
# lesson and the migrating-wazuh-indices documentation.
#
# Run as root, on EVERY indexer node you want to back up.

set -euo pipefail

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

# 1. Back up the security configuration through the plugin's own tool.
/usr/share/wazuh-indexer/bin/indexer-security-init.sh \
  --options "-backup /etc/wazuh-indexer/opensearch-security -icl -nhnv"

# 2. Create a dated destination folder.
bkp_folder=~/wazuh_files_backup/$(date +%F_%H:%M)
mkdir -p "$bkp_folder"
echo "$bkp_folder"

# 3. Save host information.
cat /etc/*release* > "$bkp_folder/host-info.txt"
echo -e "\n$(hostname): $(hostname -I)" >> "$bkp_folder/host-info.txt"

# 4. Back up the certificates and configuration files.
rsync -aREz \
  /etc/wazuh-indexer/certs/ \
  /etc/wazuh-indexer/jvm.options \
  /etc/wazuh-indexer/jvm.options.d \
  /etc/wazuh-indexer/log4j2.properties \
  /etc/wazuh-indexer/opensearch.yml \
  /etc/wazuh-indexer/opensearch.keystore \
  /etc/wazuh-indexer/opensearch-observability/ \
  /etc/wazuh-indexer/opensearch-security/ \
  /etc/wazuh-indexer/wazuh-indexer-notifications/ \
  /etc/wazuh-indexer/wazuh-indexer-notifications-core/ \
  /etc/wazuh-indexer/wazuh-indexer-reports-scheduler/ \
  /etc/wazuh-indexer/wazuh-indexer-security-analytics/ \
  /usr/lib/sysctl.d/wazuh-indexer.conf \
  "$bkp_folder"

# 5. Compress for transfer or storage.
tar -cvzf wazuh-indexer-backup.tar.gz "$bkp_folder"

echo
echo "Done: wazuh-indexer-backup.tar.gz"
echo "Restore is documented for the SAME version only. In a multi-node"
echo "deployment, restore the corresponding backup on each node."
