#!/usr/bin/env bash
# backup-nightly.sh — one job, one exit code, one dead-man ping.
# Tested on Debian 12 / bash 5.2. Ping behaviour tested with a stub restic.
set -uo pipefail

export RESTIC_REPOSITORY="${RESTIC_REPOSITORY:?}"
export RESTIC_PASSWORD_FILE="${RESTIC_PASSWORD_FILE:?}"
PING_URL="${PING_URL:-}"
APPDATA="${APPDATA:-/mnt/user/appdata}"
DUMPS="${DUMPS:-/mnt/user/dumps}"
LOG="${LOG:-/var/log/restic-nightly.log}"

exec >>"$LOG" 2>&1
echo "--- $(date -Is) starting"

# On failure: tell the monitor, then stop. Never let a step fail quietly.
die() {
  echo "FAILED: $1"
  [ -n "$PING_URL" ] && curl -fsS -m 10 "$PING_URL/fail" >/dev/null 2>&1
  exit 1
}

"$(dirname "$0")/pre-backup-dump.sh" "$APPDATA" "$DUMPS" || die "database dump"

restic backup "$APPDATA" "$DUMPS" \
  --exclude '**/thumbs' --exclude '**/cache' --exclude '*.tmp' \
  --tag nightly --host "$(hostname -s)" || die "restic backup"

restic check || die "restic check"

# Only a fully successful run pings. Silence is the alert.
[ -n "$PING_URL" ] && curl -fsS -m 10 "$PING_URL" >/dev/null 2>&1
echo "--- $(date -Is) OK"
exit 0
