#!/usr/bin/env bash
#
# sudosudo-hb — wrap any cron job with a sudosudo.dev heartbeat (dead-man switch).
#
#   sudosudo-hb <NAME> -- <command> [args...]
#
# Runs the command; on exit 0 pings the heartbeat URL, otherwise pings <url>/fail
# with the exit code and the last lines of output. The command's own exit code
# and output are passed through unchanged, so it drops into an existing crontab:
#
#   */5 * * * *  sudosudo-hb OPS_SCAN -- /path/run-cron.sh ops-scan
#
# The URL comes from the env var SUDOSUDO_HB_URL_<NAME>, or else from the line
# `SUDOSUDO_HB_URL_<NAME>=...` in $SUDOSUDO_HB_ENV (default ~/.config/sudosudo/hb.env,
# keep it chmod 600 — the URL is the credential). No URL → just runs the command.
# Create the probe with `sudosudo probe add <target> --heartbeat --name ... --interval N`.

set -uo pipefail

NAME="${1:-}"
if [ -z "$NAME" ] || [ "${2:-}" != "--" ] || [ $# -lt 3 ]; then
  echo "usage: $(basename "$0") <NAME> -- <command> [args...]" >&2
  exit 2
fi
shift 2

VAR="SUDOSUDO_HB_URL_${NAME}"
URL="${!VAR:-}"
ENV_FILE="${SUDOSUDO_HB_ENV:-$HOME/.config/sudosudo/hb.env}"
if [ -z "$URL" ] && [ -r "$ENV_FILE" ]; then
  URL="$(grep -m1 -E "^${VAR}=" "$ENV_FILE" | cut -d= -f2- | tr -d '"'"'"'\r')"
fi

OUT="$(mktemp)"
trap 'rm -f "$OUT"' EXIT

"$@" > >(tee -a "$OUT") 2> >(tee -a "$OUT" >&2)
CODE=$?
wait  # let the tee processes flush

if [ -n "$URL" ]; then
  if [ "$CODE" -eq 0 ]; then
    curl -fsS -m 10 -o /dev/null "$URL" 2>/dev/null || true
  else
    { echo "exit $CODE"; tail -c 400 "$OUT"; } | head -c 500 |
      curl -fsS -m 10 -o /dev/null -X POST --data-binary @- "$URL/fail" 2>/dev/null || true
  fi
fi
exit "$CODE"
