#!/usr/bin/env bash
#
# Alerts to Answers — Laboratory Reset  ·  Version 15
# (c) Dr. Furstenberg. All rights reserved.
#
# Resets WAZUH-SRV to a clean state: empties the flat alert logs and removes the
# indexed alert documents so the Dashboard opens on an empty Security Events view.
#
# The indices themselves are NOT deleted. Documents are removed with
# delete_by_query, which preserves index templates, mappings, and any index
# state management policy. Deleting indices outright can leave the deployment
# unable to write new alerts until templates are rebuilt.
#
# LABORATORY USE ONLY. Do not run on any production system.
#
# Run order:  1) WIN11   2) UB2604   3) wait 60s   4) WAZUH-SRV
# Companion guide: Student Lab Reset Guide, Part 3
#
# Usage:  chmod +x reset-lab-wazuh-srv_v18.sh
#         sudo ./reset-lab-wazuh-srv_v18.sh

set -uo pipefail

GREEN='\033[0;32m'; YELLOW='\033[0;33m'; RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'
ok()   { echo -e "${GREEN}$*${NC}"; }
warn() { echo -e "${YELLOW}$*${NC}"; }
err()  { echo -e "${RED}$*${NC}"; }
head_() { echo; echo -e "${CYAN}$*${NC}"; }

INDEXER="https://localhost:9200"
INDEX_PATTERN="wazuh-alerts-*"          # scope is fixed - never a bare wildcard
ARCHIVE_PATTERN="wazuh-archives-*"

# Flat log files emptied by this script.
FLAT_LOGS=(
  "/var/ossec/logs/alerts/alerts.json"
  "/var/ossec/logs/alerts/alerts.log"
  "/var/ossec/logs/archives/archives.json"
  "/var/ossec/logs/archives/archives.log"
  "/var/ossec/logs/ossec.log"
)

# ------------------------------------------------------------------ privilege
if [[ $EUID -ne 0 ]]; then
  err "This script must be run with sudo."
  echo "Try:  sudo ./reset-lab-wazuh-srv_v18.sh"
  exit 1
fi

head_ "Alerts to Answers - Reset WAZUH-SRV"
echo "-----------------------------------------"

command -v curl >/dev/null 2>&1 || { err "curl is required but not installed."; exit 1; }

# ------------------------------------------------------------------ password
echo
echo "The Wazuh Indexer admin password is required."
echo "If you do not have it, cancel and run:"
echo "  sudo tar -O -xvf wazuh-install-files.tar wazuh-install-files/wazuh-passwords.txt"
echo
read -r -s -p "Indexer admin password: " INDEXER_PW
echo
if [[ -z "$INDEXER_PW" ]]; then
  err "No password entered. Nothing was changed."
  exit 1
fi

# ------------------------------------------------------------------ auth test
http_code=$(curl -s -k -o /dev/null -w '%{http_code}' \
  -u "admin:${INDEXER_PW}" "${INDEXER}/_cluster/health" 2>/dev/null || echo "000")

if [[ "$http_code" == "401" ]]; then
  err "Could not authenticate to the Indexer (HTTP 401)."
  echo "The password was not accepted. Nothing was changed. Run the script again."
  exit 1
elif [[ "$http_code" != "200" ]]; then
  err "Could not reach the Indexer (HTTP ${http_code})."
  echo "Confirm the wazuh-indexer service is running. Nothing was changed."
  exit 1
fi
ok "Authenticated to the Indexer."

# ------------------------------------------------------------------ pre-flight
doc_count=$(curl -s -k -u "admin:${INDEXER_PW}" \
  "${INDEXER}/${INDEX_PATTERN}/_count" 2>/dev/null \
  | grep -o '"count":[0-9]*' | head -1 | cut -d: -f2)
doc_count=${doc_count:-0}

echo
echo "This script will:"
echo "  - Remove indexed alert documents from ${INDEX_PATTERN}  (${doc_count} documents)"
echo "  - Remove indexed documents from ${ARCHIVE_PATTERN} if present"
echo "  - Empty these flat log files:"
for f in "${FLAT_LOGS[@]}"; do
  [[ -f "$f" ]] && printf "      %-46s (%s bytes)\n" "$f" "$(stat -c%s "$f" 2>/dev/null || echo 0)"
done
echo
echo "It will NOT:"
echo "  - Delete any index, template, mapping, or ISM policy"
echo "  - Uninstall or reconfigure Wazuh"
echo "  - Remove agents, rules, decoders, or the agent keys file"
echo "  - Touch any index outside the two patterns listed above"
echo

# ------------------------------------------------------------------ confirm
read -r -p "Type RESET to continue (anything else cancels): " answer
if [[ "$answer" != "RESET" ]]; then
  warn "Cancelled. Nothing was changed."
  exit 0
fi

# ------------------------------------------------------------------ flat logs
echo
for f in "${FLAT_LOGS[@]}"; do
  if [[ -f "$f" ]]; then
    if : > "$f" 2>/dev/null; then echo "Emptied: $f"; else err "Could not empty: $f"; fi
  fi
done

# ------------------------------------------------------------------ indexed docs
delete_docs () {
  local pattern="$1"
  local resp
  resp=$(curl -s -k -u "admin:${INDEXER_PW}" \
    -X POST "${INDEXER}/${pattern}/_delete_by_query?refresh=true&conflicts=proceed" \
    -H 'Content-Type: application/json' \
    -d '{"query":{"match_all":{}}}' 2>/dev/null)
  echo "$resp" | grep -o '"deleted":[0-9]*' | head -1 | cut -d: -f2
}

deleted=$(delete_docs "$INDEX_PATTERN"); deleted=${deleted:-0}
ok "Removed ${deleted} document(s) from ${INDEX_PATTERN}"

arch_deleted=$(delete_docs "$ARCHIVE_PATTERN"); arch_deleted=${arch_deleted:-0}
if [[ "$arch_deleted" != "0" ]]; then
  ok "Removed ${arch_deleted} document(s) from ${ARCHIVE_PATTERN}"
fi

# ------------------------------------------------------------------ restart
echo
echo "Restarting the Wazuh Manager so new alerts flow cleanly..."
systemctl restart wazuh-manager >/dev/null 2>&1
sleep 5

# ------------------------------------------------------------------ verify
echo
echo "Alert indices after reset:"
curl -s -k -u "admin:${INDEXER_PW}" \
  "${INDEXER}/_cat/indices/${INDEX_PATTERN}?v&h=index,docs.count,store.size" 2>/dev/null \
  || warn "Could not list indices."

echo
echo "Wazuh services:"
for svc in wazuh-manager wazuh-indexer wazuh-dashboard; do
  if systemctl is-active --quiet "$svc"; then
    ok "  ${svc}: running"
  else
    err "  ${svc}: NOT running"
  fi
done

echo
ok "WAZUH-SRV reset complete."
echo "Verify in the Dashboard: Security Events should now be empty."
echo "Then generate one fresh event on WIN11 to confirm the pipeline still works."
unset INDEXER_PW
exit 0
