#!/usr/bin/env bash
# hb-run: run a command and report start / exit code / last 10KB of output to a heartbeat check.
#
#   hb-run [-u PING_URL] [-m SECONDS] [-q] -- command [args...]
#
# PING_URL defaults to $HB_URL (e.g. http://host:8106/ping/<uuid>). The wrapped command's
# exit code is returned unchanged, and a failing ping never makes the job itself fail.
set -u

url="${HB_URL:-}"
timeout=10
quiet=0
usage() { echo "usage: hb-run [-u PING_URL] [-m SECONDS] [-q] -- command [args...]" >&2; exit 2; }

while getopts "u:m:qh" opt; do
  case "$opt" in
    u) url="$OPTARG" ;;
    m) timeout="$OPTARG" ;;
    q) quiet=1 ;;
    *) usage ;;
  esac
done
shift $((OPTIND - 1))
[ "${1:-}" = "--" ] && shift
[ $# -gt 0 ] || usage
[ -n "$url" ] || { echo "hb-run: no ping URL (use -u or set HB_URL)" >&2; exit 2; }
url="${url%/}"

ping() {
  curl -fsS -m "$timeout" --retry 3 -A "hb-run/1.0" "$@" >/dev/null 2>&1 \
    || { [ "$quiet" = 1 ] || echo "hb-run: warning: ping to $url failed" >&2; }
}

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

ping "$url/start"
"$@" 2>&1 | tee "$out"
code=${PIPESTATUS[0]}
tail -c 10240 "$out" > "$out.tail" && mv "$out.tail" "$out"
ping --data-binary "@$out" "$url/$code"
exit "$code"
