#!/usr/bin/env bash
# =============================================================================
# setup-monitoring-agents.sh — Provisionne TOUS les agents d'observabilité
# Lib-Lab — sur un nouvel hôte, en une commande.
#   1) node_exporter   (métriques  → scrappé par Prometheus / srv-obs)
#   2) zabbix-agent    (supervision → serveur Zabbix)
#   3) promtail        (logs        → Loki / srv-obs:3100)
# -----------------------------------------------------------------------------
# Récupère les scripts unitaires depuis files.lib-lab.tech puis les enchaîne.
# Usage :
#   sudo bash setup-monitoring-agents.sh
#   sudo ZBX_SERVER=172.0.16.80 LOKI_HOST=172.0.16.80 bash setup-monitoring-agents.sh --yes
# Variables :
#   BASE_URL    (défaut https://files.lib-lab.tech/script/linux)
#   ZBX_SERVER  (défaut 172.0.16.245 — passer à 172.0.16.80 après migration)
#   LOKI_HOST   (défaut 172.0.16.80)
#   LOGS_AGENT  alloy (défaut) | promtail (EOL)
#   SKIP        liste séparée par espaces parmi: node zabbix logs
# =============================================================================
set -uo pipefail
die(){ echo "ERROR: $*" >&2; exit 1; }
msg(){ echo -e "\n========== $* =========="; }
ok(){  echo "[✓] $*"; }

[[ ${EUID:-$(id -u)} -eq 0 ]] || die "Exécute en root (sudo $0)."

BASE_URL="${BASE_URL:-https://files.lib-lab.tech/script/linux}"
ZBX_SERVER="${ZBX_SERVER:-172.0.16.245}"
LOKI_HOST="${LOKI_HOST:-172.0.16.80}"
SKIP="${SKIP:-}"
ASSUME_YES="false"
[[ "${1:-}" == "--yes" ]] && ASSUME_YES="true"

command -v curl >/dev/null 2>&1 || { apt-get update -y && apt-get install -y curl; }

run_remote(){ # run_remote <script> [args...]
  local script="$1"; shift || true
  local tmp; tmp="$(mktemp)"
  msg "Téléchargement $script"
  curl -fsSL "${BASE_URL}/${script}" -o "$tmp" || { echo "[!] échec téléchargement $script"; return 1; }
  chmod +x "$tmp"
  bash "$tmp" "$@"
  local rc=$?
  rm -f "$tmp"
  return $rc
}

skip(){ echo " $SKIP " | grep -q " $1 "; }

echo "Provisioning agents observabilité sur $(hostname) :"
echo "  - Zabbix server : ${ZBX_SERVER}"
echo "  - Loki          : ${LOKI_HOST}:3100"
echo "  - Skip          : ${SKIP:-<aucun>}"
if [[ "$ASSUME_YES" != "true" ]]; then
  read -r -p "Continuer ? [O/n] " a; [[ "${a,,}" == "n" ]] && exit 0
fi

# 1) node_exporter
if ! skip node; then
  msg "1/3 — node_exporter"
  run_remote node-exporter.sh && ok "node_exporter OK" || echo "[!] node_exporter en échec"
fi

# 2) zabbix-agent (non interactif via --server --yes)
if ! skip zabbix; then
  msg "2/3 — zabbix-agent (serveur ${ZBX_SERVER})"
  run_remote agent-zabbix.sh --server "${ZBX_SERVER}" --yes && ok "zabbix-agent OK" || echo "[!] zabbix-agent en échec"
fi

# 3) logs → Loki  (Alloy par défaut ; Promtail = EOL, dispo en fallback)
LOGS_AGENT="${LOGS_AGENT:-alloy}"
if ! skip logs && ! skip promtail; then
  msg "3/3 — logs via ${LOGS_AGENT} (Loki ${LOKI_HOST}:3100)"
  if [[ "$LOGS_AGENT" == "promtail" ]]; then
    LOKI_HOST="${LOKI_HOST}" run_remote agent-promtail.sh --yes && ok "promtail OK" || echo "[!] promtail en échec"
  else
    LOKI_HOST="${LOKI_HOST}" run_remote agent-alloy.sh --yes && ok "alloy OK" || echo "[!] alloy en échec"
  fi
fi

msg "Terminé"
echo "Vérifs rapides :"
echo "  systemctl status node_exporter zabbix-agent promtail --no-pager"
echo "  → Ajouter $(hostname -I | awk '{print $1}'):9100 aux cibles Prometheus de srv-obs"
