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

# =====================
# Configuration
# =====================
CMK_SERVER="cmk.bashclub.org"
CMK_USER="cmkpush"
CMK_PORT="22"
REMOTE_BASE="/var/lib/cmk-push-agent"
HOSTNAME="$(hostname -f 2>/dev/null || hostname)"

source /etc/cmk-push-agent/cmk-push-agent.conf

# jitter to avoid thundering herd (0–20s)
# sleep $(( RANDOM % 20 ))

TMP="$(mktemp)"
TMP_GZ="${TMP}.gz"

cleanup() {
  rm -f "$TMP" "$TMP_GZ"
}
trap cleanup EXIT

# =====================
# Collect agent output
# =====================
/usr/bin/check_mk_agent > "$TMP"

# compress (important for scale)
gzip -c "$TMP" > "$TMP_GZ"

# =====================
# Atomic upload
# =====================
ssh -T \
  -o BatchMode=yes \
  -o ConnectTimeout=10 \
  -o StrictHostKeyChecking=yes \
  -o IPQoS=throughput \
  -p "${CMK_PORT}" \
  "${CMK_USER}@${CMK_SERVER}" \
  -- --fqdn "${HOSTNAME}" \
  < "$TMP_GZ"