#!/usr/bin/env bash
#
# Durable offsite backup for the self-hosted VPS (systemd + Neon, NOT docker).
#
# This is the backup that lets Gluecron drop the GitHub mirror safely: it is
# the ONLY off-box copy of the bare git repos once GitHub is gone. It captures
# both halves of the platform's state:
#
#   1. the bare git repos under $GIT_REPOS_PATH  (the actual repo objects —
#      the DB only stores metadata and CANNOT reconstruct these)
#   2. the Neon Postgres database via pg_dump over $DATABASE_URL
#
# ...then pushes both to an offsite bucket with rclone and pings a
# dead-man's-switch so a silently-missed backup pages you.
#
# Install as a systemd timer (see docs/CUTOVER_RUNBOOK.md). Run daily.
#
# Required env (set in /etc/gluecron.env):
#   DATABASE_URL          Neon connection string (postgresql://...)
#   BACKUP_RCLONE_REMOTE  e.g. r2:gluecron-backups  (rclone must be configured)
# Optional env:
#   GIT_REPOS_PATH        bare repos dir (default: /opt/gluecron/repos)
#   BACKUP_DIR            local staging dir (default: /opt/gluecron/backups)
#   RETAIN_DAYS           local + offsite retention (default: 14)
#   HEALTHCHECK_PING_URL  https://hc-ping.com/<uuid>  (healthchecks.io)
set -euo pipefail

GIT_REPOS_PATH="${GIT_REPOS_PATH:-/opt/gluecron/repos}"
BACKUP_DIR="${BACKUP_DIR:-/opt/gluecron/backups}"
RETAIN_DAYS="${RETAIN_DAYS:-14}"

log() { echo "$(date -Is) [backup-offsite] $*"; }

if [ -z "${DATABASE_URL:-}" ]; then
  log "FATAL: DATABASE_URL is not set — cannot back up the database."
  exit 1
fi

mkdir -p "$BACKUP_DIR"
ts=$(date +%Y%m%d-%H%M%S)
repos_out="$BACKUP_DIR/repos-$ts.tar.gz"
db_out="$BACKUP_DIR/db-$ts.dump"

# 1. Bare git repos — the irreplaceable half. tar the whole tree; bare repos
#    are self-contained so a plain tar is a valid, restorable snapshot.
if [ -d "$GIT_REPOS_PATH" ]; then
  tar -czf "$repos_out" -C "$(dirname "$GIT_REPOS_PATH")" "$(basename "$GIT_REPOS_PATH")"
  log "repos snapshot: $repos_out ($(du -h "$repos_out" | cut -f1))"
else
  log "WARN: GIT_REPOS_PATH ($GIT_REPOS_PATH) does not exist — skipping repos snapshot"
fi

# 2. Database — custom format so pg_restore can do selective/parallel restore.
pg_dump --format=custom --no-owner --no-privileges "$DATABASE_URL" > "$db_out"
log "db dump: $db_out ($(du -h "$db_out" | cut -f1))"

# 3. Offsite copy (both artifacts). Fail LOUD if configured but the copy fails —
#    a backup that only lives on the same box it protects is not a backup.
if [ -n "${BACKUP_RCLONE_REMOTE:-}" ]; then
  if ! command -v rclone >/dev/null 2>&1; then
    log "FATAL: BACKUP_RCLONE_REMOTE set but rclone is not installed"
    exit 1
  fi
  rclone copy "$db_out" "$BACKUP_RCLONE_REMOTE/db/" \
    && log "offsite: db -> $BACKUP_RCLONE_REMOTE/db/" \
    || { log "FATAL: offsite db copy failed"; exit 1; }
  if [ -f "$repos_out" ]; then
    rclone copy "$repos_out" "$BACKUP_RCLONE_REMOTE/repos/" \
      && log "offsite: repos -> $BACKUP_RCLONE_REMOTE/repos/" \
      || { log "FATAL: offsite repos copy failed"; exit 1; }
  fi
  # Prune offsite copies older than retention (best-effort).
  rclone delete --min-age "${RETAIN_DAYS}d" "$BACKUP_RCLONE_REMOTE/db/" 2>/dev/null || true
  rclone delete --min-age "${RETAIN_DAYS}d" "$BACKUP_RCLONE_REMOTE/repos/" 2>/dev/null || true
else
  log "WARN: BACKUP_RCLONE_REMOTE not set — backup is LOCAL ONLY (not safe as the sole copy once GitHub is gone)"
fi

# 4. Local retention.
find "$BACKUP_DIR" -name 'repos-*.tar.gz' -mtime +"$RETAIN_DAYS" -delete 2>/dev/null || true
find "$BACKUP_DIR" -name 'db-*.dump'      -mtime +"$RETAIN_DAYS" -delete 2>/dev/null || true

# 5. Dead-man's-switch: only ping on full success (reached the end of the script).
if [ -n "${HEALTHCHECK_PING_URL:-}" ]; then
  curl -fsS -m 10 "$HEALTHCHECK_PING_URL" >/dev/null 2>&1 || true
fi

log "done."
