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

health_url=${PUSHY_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/pushy/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='pushy-systemd swap' provisions a swap file and re-derives the limits"
fi
if [[ -e /etc/pushy/worker-disabled ]]; then
  echo "role=api-only worker=disabled"
else
  echo "role=api-worker worker=enabled"
fi
for unit in pushy.target pushy-api.service pushy-api-candidate.service pushy-worker.service pushy-dailyjob.timer pushy-cresc-ai-marketing.timer pushy-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 pushy-api.service pushy-api-candidate.service pushy-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 pushy-dailyjob.timer pushy-cresc-ai-marketing.timer pushy-health-watchdog.timer --no-pager
for slot_unit_socket in \
  primary:pushy-api.service:/run/pushy/metrics.sock \
  candidate:pushy-api-candidate.service:/run/pushy-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
