#!/bin/sh
set -eu

# Pushes backup.sh's local backups to an off-host restic repository so
# production member data survives loss of the machine or disk itself, not
# just accidental deletion (see README "Backups"). restic encrypts
# everything client-side before upload, so RESTIC_PASSWORD protects the
# data even if the remote bucket credentials leak.
#
# No-op until RESTIC_REPOSITORY/RESTIC_PASSWORD are configured in
# /etc/harbor/harbor.env — safe to enable the timer before picking a
# provider.

BACKUP_DIR=${BACKUP_DIR:-/var/backups/harbor}
BACKUP_STATUS_DIR=${BACKUP_STATUS_DIR:-/opt/harbor/deploy/backup/status}
OFFSITE_BACKUP_RETENTION_DAYS=${OFFSITE_BACKUP_RETENTION_DAYS:-30}

if [ -z "${RESTIC_REPOSITORY:-}" ] || { [ -z "${RESTIC_PASSWORD:-}" ] && [ -z "${RESTIC_PASSWORD_FILE:-}" ]; }; then
  printf '%s\n' "offsite-sync: RESTIC_REPOSITORY/RESTIC_PASSWORD not configured, skipping" >&2
  exit 0
fi

if ! command -v restic >/dev/null 2>&1; then
  printf '%s\n' "offsite-sync: restic not installed" >&2
  exit 1
fi

if [ ! -d "$BACKUP_DIR" ] || [ -z "$(find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d ! -name '.*.tmp' -print -quit)" ]; then
  printf '%s\n' "offsite-sync: no local backup found under $BACKUP_DIR yet, skipping" >&2
  exit 0
fi

host_tag=$(hostname)

restic snapshots >/dev/null 2>&1 || restic init

restic backup --tag harbor-backup --host "$host_tag" "$BACKUP_DIR"
restic forget --tag harbor-backup --host "$host_tag" --keep-within "${OFFSITE_BACKUP_RETENTION_DAYS}d" --prune

mkdir -p "$BACKUP_STATUS_DIR"
marker_tmp="$BACKUP_STATUS_DIR/.haixun_offsite_backup.prom.tmp"
{
  printf '# HELP haixun_offsite_backup_last_success_timestamp_seconds Unix timestamp of the last successful offsite backup sync.\n'
  printf '# TYPE haixun_offsite_backup_last_success_timestamp_seconds gauge\n'
  printf 'haixun_offsite_backup_last_success_timestamp_seconds %s\n' "$(date -u +%s)"
} > "$marker_tmp"
chmod 0644 "$marker_tmp"
mv "$marker_tmp" "$BACKUP_STATUS_DIR/haixun_offsite_backup.prom"

printf '%s\n' "offsite-sync: pushed $BACKUP_DIR to $RESTIC_REPOSITORY"
