#!/usr/bin/env bash
set -euo pipefail

health_url=${CRESC_HEALTH_URL:-http://127.0.0.1:9000/status}
memory_total_bytes=$(awk '$1 == "MemTotal:" { printf "%.0f", $2 * 1024; exit }' /proc/meminfo 2>/dev/null || echo unknown)
swappiness=$(sysctl -n vm.swappiness 2>/dev/null || echo unknown)
swap_bytes=$(awk 'NR > 1 { total += $3 * 1024 } END { printf "%.0f", total + 0 }' /proc/swaps 2>/dev/null || echo unknown)

echo "release=$(readlink -f /opt/cresc/current 2>/dev/null || echo missing)"
echo "host-memory total_bytes=$memory_total_bytes swappiness=$swappiness swap_bytes=$swap_bytes"
if [[ $swap_bytes == 0 ]]; then
  # Without swap a cgroup cannot reclaim anonymous memory, so MemoryHigh stops
  # being a soft limit and becomes a permanent throttle once crossed.
  echo "host-memory warning=no-swap hint='cresc-systemd swap' provisions a swap file and re-derives the limits"
fi
if [[ -e /etc/cresc/worker-disabled ]]; then
  echo "role=api-only worker=disabled"
else
  echo "role=api-worker worker=enabled"
fi
for unit in cresc.target cresc-api.service cresc-api-candidate.service cresc-worker.service cresc-dailyjob.timer cresc-health-watchdog.timer; do
  echo "$unit active=$(systemctl is-active "$unit" 2>/dev/null || true) enabled=$(systemctl is-enabled "$unit" 2>/dev/null || true)"
done

systemctl show cresc-api.service cresc-api-candidate.service cresc-worker.service \
  -p Id -p MainPID -p NRestarts -p MemoryCurrent -p MemoryPeak \
  -p MemoryHigh -p MemoryMax -p MemorySwapCurrent -p MemorySwapPeak \
  -p MemorySwapMax -p OOMScoreAdjust
systemctl list-timers cresc-dailyjob.timer cresc-health-watchdog.timer --no-pager
for slot_unit_socket in \
  primary:cresc-api.service:/run/cresc/metrics.sock \
  candidate:cresc-api-candidate.service:/run/cresc-api-candidate/metrics.sock; do
  slot=${slot_unit_socket%%:*}
  unit_socket=${slot_unit_socket#*:}
  unit=${unit_socket%%:*}
  socket_path=${unit_socket#*:}
  if ! systemctl is-active --quiet "$unit"; then
    echo "api-slot=$slot inactive"
    continue
  fi
  printf 'api-slot=%s ' "$slot"
  curl --fail --silent --show-error --max-time 5 \
    --unix-socket "$socket_path" http://localhost/health
  echo
done
curl --fail --silent --show-error --max-time 5 "$health_url"
echo
