Files
Heimdall/docker/scripts/backup-protected-data.sh
T

49 lines
2.4 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
# Archive the shared Central data volume, including local objects and the
# encrypted ASP.NET Data Protection key ring.
set -euo pipefail
SOURCE_DIR="${HEIMDALL_DATA_SOURCE:-/source/heimdall_data}"
BACKUP_DIR="${BACKUP_LOCAL_DIR:-/backups}"
RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}"
S3_ENDPOINT="${RUSTFS_ENDPOINT:-${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}}"
S3_ACCESS_KEY="${RUSTFS_ACCESS_KEY:-${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}}"
S3_SECRET_KEY="${RUSTFS_SECRET_KEY:-${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}}"
S3_BUCKET="${RUSTFS_BUCKET:-${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}}"
SKIP_S3_UPLOAD="${BACKUP_SKIP_S3_UPLOAD:-0}"
TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
ARCHIVE_DIR="${BACKUP_DIR}/protected-data"
ARCHIVE="${ARCHIVE_DIR}/heimdall-data-${TIMESTAMP}.tar.gz"
log() { echo "[protected-data-backup] $(date -u +%H:%M:%S) $*"; }
die() { log "FATAL: $*" >&2; exit 1; }
[[ -d "$SOURCE_DIR/dp-keys" ]] || die "Data Protection key directory is missing: $SOURCE_DIR/dp-keys"
[[ "$RETENTION_DAYS" =~ ^[0-9]+$ ]] || die "BACKUP_RETENTION_DAYS must be a non-negative integer"
mkdir -p "$ARCHIVE_DIR"
TEMP_ARCHIVE="${ARCHIVE}.tmp"
trap 'rm -f "$TEMP_ARCHIVE"' EXIT
tar -czf "$TEMP_ARCHIVE" -C "$SOURCE_DIR" .
chmod 0600 "$TEMP_ARCHIVE"
mv "$TEMP_ARCHIVE" "$ARCHIVE"
log "Created protected data archive: $ARCHIVE"
find "$ARCHIVE_DIR" -type f -name 'heimdall-data-*.tar.gz' -mtime "+$RETENTION_DAYS" -delete
# Store an off-site copy when S3-compatible credentials are configured.
if [[ "$SKIP_S3_UPLOAD" == "1" ]]; then
log "S3 upload disabled by BACKUP_SKIP_S3_UPLOAD"
elif [[ -n "$S3_ENDPOINT" && -n "$S3_ACCESS_KEY" && -n "$S3_SECRET_KEY" ]]; then
if command -v mc >/dev/null 2>&1; then
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null
mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
elif command -v aws >/dev/null 2>&1; then
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$ARCHIVE" "s3://${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
else
die "Neither mc nor aws CLI is available to upload protected data backups"
fi
log "Uploaded protected data archive to the configured object store"
else
log "S3 credentials are not configured; the archive remains in the local backup volume"
fi