#!/usr/bin/env bash
#
# Create a timestamped Metacrypt database backup and prune old ones.
#
# Usage: ./backup.sh [retention_days]
#   retention_days: number of days to keep backups (default: 30)
#
set -euo pipefail

CONFIG="${METACRYPT_CONFIG:-/srv/metacrypt/metacrypt.toml}"
BACKUP_DIR="${METACRYPT_BACKUP_DIR:-/srv/metacrypt/backups}"
RETENTION_DAYS="${1:-30}"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_FILE="${BACKUP_DIR}/metacrypt-${TIMESTAMP}.db"

echo "==> Creating backup: ${BACKUP_FILE}"
metacrypt snapshot --config "$CONFIG" --output "$BACKUP_FILE"

echo "==> Pruning backups older than ${RETENTION_DAYS} days"
find "$BACKUP_DIR" -name 'metacrypt-*.db' -mtime "+${RETENTION_DAYS}" -delete -print

echo "==> Done"
ls -lh "$BACKUP_DIR"/metacrypt-*.db 2>/dev/null | tail -5
