#!/usr/bin/env bash
# Arms the node_exporter textfile producers and proves they are actually producing.
#
# Single source of truth for the producer set, its cadences, and its arming. Run by
# grafana/install-dashboards.sh on a full provision and by packaging/deploy-local.sh on
# every deploy, so a lost enablement is re-asserted instead of silently going blind.
set -Eeuo pipefail

TEXTFILE_DIR="/var/lib/node_exporter/textfile"
LIB_DIR="/usr/local/lib/system-monitor"

# producer|cadence|metric file it must refresh ("-" = emits only when configured)
PRODUCERS=(
  "mem_exhaustion.py|15s|mem_exhaustion.prom"
  "cpu_nonbuild.py|15s|cpu_nonbuild.prom"
  "tmpfs_junk.py|30s|tmpfs_junk.prom"
  "smartmon.sh|5m|smartmon.prom"
  "backup_age.py|1h|-"
)

fail() { printf '[FAIL] %s\n' "$*" >&2; exit 1; }

[[ "${EUID}" -eq 0 ]] || fail "run as root, for example: deck-sudo bash $0"
[[ -f /etc/systemd/system/node-textfile@.timer ]] ||
  fail "node-textfile@.timer is not installed — run grafana/install-dashboards.sh first"

for entry in "${PRODUCERS[@]}"; do
  IFS='|' read -r producer cadence _ <<<"$entry"
  [[ -x "$LIB_DIR/$producer" ]] || fail "producer $LIB_DIR/$producer is missing or not executable"
  install -d -m0755 "/etc/systemd/system/node-textfile@${producer}.timer.d"
  cat >"/etc/systemd/system/node-textfile@${producer}.timer.d/override.conf" <<EOF
[Timer]
OnUnitActiveSec=
OnUnitActiveSec=${cadence}
EOF
done

systemctl daemon-reload

for entry in "${PRODUCERS[@]}"; do
  IFS='|' read -r producer _ _ <<<"$entry"
  timer="node-textfile@${producer}.timer"
  systemctl enable --now "$timer" >/dev/null
  # Priming the service supplies the OnUnitActiveSec base for the very first interval.
  systemctl start "node-textfile@${producer}.service" || fail "first run failed for $producer"
  next="$(systemctl show "$timer" -P NextElapseUSecMonotonic)"
  [[ -n "$next" && "$next" != "infinity" ]] ||
    fail "$timer is enabled but not armed (NextElapseUSecMonotonic=${next:-unset}) — it would never fire"
done

# Arming is not production: prove each producer's metric file was refreshed just now.
now="$(date +%s)"
for entry in "${PRODUCERS[@]}"; do
  IFS='|' read -r producer _ metric <<<"$entry"
  [[ "$metric" == "-" ]] && continue
  path="$TEXTFILE_DIR/$metric"
  [[ -f "$path" ]] || fail "$producer produced no $path"
  age=$(( now - $(stat -c %Y "$path") ))
  [[ "$age" -le 120 ]] || fail "$path is ${age}s old after priming $producer — the producer is not writing"
done

printf 'node_exporter textfile producers armed and producing: %s\n' "${PRODUCERS[*]%%|*}"
