#!/usr/bin/env bash
# Nightly pg_dump into the workspace `backups/` directory.
#
# THIS IS A HEDGE, NOT A BACKUP. The dump lands on the same disk as the
# database it protects, so it survives an accidental DROP but not a disk
# failure. The real answer is the server-wide backup substrate (v8 T4.8), which
# is not built. Recorded in brief.md known gaps.
#
# Schedule (rian's crontab, needs his own shell):
#   15 3 * * * /srv/apps/coachpapa/main/scripts/backup-db.sh
set -euo pipefail

CONTAINER="${CP_DB_CONTAINER:-coachpapa-db}"
OUT_DIR="${CP_BACKUP_DIR:-/srv/apps/coachpapa/backups}"
KEEP_DAYS="${CP_BACKUP_KEEP_DAYS:-14}"

mkdir -p "$OUT_DIR"
stamp="$(date +%Y%m%d-%H%M%S)"
target="$OUT_DIR/coachpapa-$stamp.sql.gz"

docker exec "$CONTAINER" pg_dump -U coachpapa -d coachpapa | gzip > "$target"
chmod 640 "$target"

# Fail loudly on an empty dump rather than quietly keeping a useless file.
if [ ! -s "$target" ]; then
  echo "backup produced an empty file: $target" >&2
  exit 1
fi

find "$OUT_DIR" -name 'coachpapa-*.sql.gz' -mtime "+$KEEP_DAYS" -delete
echo "backup written: $target ($(du -h "$target" | cut -f1))"
