#!/usr/bin/env bash
# Daily backup — Nextcloud data + PostgreSQL dump (Spec 034)
set -euo pipefail

STACK_DIR="${STACK_DIR:-/opt/vm116-nextcloud}"
BACKUP_ROOT="${BACKUP_ROOT:-/var/backups/nextcloud}"
STAMP=$(date +%Y%m%d-%H%M)

mkdir -p "$BACKUP_ROOT/$STAMP"
cd "$STACK_DIR"

docker compose exec -T db pg_dump -U nextcloud nextcloud | gzip > "$BACKUP_ROOT/$STAMP/postgres.sql.gz"
docker compose exec -T -u www-data nextcloud occ maintenance:mode --on
docker run --rm \
  -v vm116-nextcloud_nc-data:/data:ro \
  -v "$BACKUP_ROOT/$STAMP":/backup \
  alpine tar czf /backup/nc-data.tar.gz -C /data .
docker compose exec -T -u www-data nextcloud occ maintenance:mode --off

find "$BACKUP_ROOT" -maxdepth 1 -type d -mtime +7 -exec rm -rf {} + 2>/dev/null || true
echo "Backup: $BACKUP_ROOT/$STAMP"
