#!/usr/bin/env bash
# Timer wrapper: run the backup, alert on ntfy (NTFY_URL in the env file) on exit >= 1.
set -uo pipefail
ENV_FILE="${HOSTREPO_ENV:-/etc/hostrepo/hostrepo.env}"
# shellcheck source=/dev/null
[[ -r "$ENV_FILE" ]] && { set -a; . "$ENV_FILE"; set +a; }
out=$(mktemp); trap 'rm -f "$out"' EXIT
started=$(date -u +%s)
nice -n 10 ionice -c3 /opt/hostrepo/hostrepo-backup "$@" 2>&1 | tee "$out"; rc=${PIPESTATUS[0]}
# One status record per run, for the status page: the result, the duration,
# and the numbers the backup wrote. Never blocks or changes the exit code.
if [[ " $* " != *" --dry-run "* && " $* " != *" --no-upload "* ]]; then
  CONF="${HOSTREPO_CONF:-/etc/hostrepo/host.conf}"
  # shellcheck source=/dev/null
  HOST_ID=$(. "$CONF" && echo "$HOST_ID")
  run="${HOSTREPO_DIR:-/var/backups/hostrepo}/$HOST_ID/meta/run.json"
  { [[ -s "$run" ]] && cat "$run" || echo '{}'; } |
    jq -c --argjson rc "$rc" --argjson started "$started" --argjson ended "$(date -u +%s)" \
      '. + {kind: "backup", result: $rc, started: ($started | todate), ended: ($ended | todate), duration_s: ($ended - $started)}' |
    "$(dirname "$0")/hostrepo-status" put "$HOST_ID" backup || true
fi
if [[ $rc -ge 1 && -n "${NTFY_URL:-}" ]]; then
  { echo "exit $rc ($([[ $rc -ge 2 ]] && echo FAILED || echo warnings))"
    grep -E 'WARN|FATAL' "$out" | cut -c1-200 | head -12 || tail -n 5 "$out"; } |
    curl -s -m 20 -H "Title: host backup: $(hostname)" -H "Priority: $([[ $rc -ge 2 ]] && echo high || echo default)" \
      -H "Tags: $([[ $rc -ge 2 ]] && echo rotating_light || echo warning)" --data-binary @- "$NTFY_URL" >/dev/null || true
fi
exit "$rc"
