#!/usr/bin/env bash # Restore a protected-data archive into the mounted Heimdall data volume. set -euo pipefail SOURCE_DIR="${HEIMDALL_DATA_SOURCE:-/source/heimdall_data}" RESTORE_DIR="" FILE="" AUTO_YES=0 log() { echo "[protected-data-restore] $(date -u +%H:%M:%S) $*"; } die() { log "FATAL: $*" >&2; exit 1; } while [[ $# -gt 0 ]]; do case "$1" in --file) [[ $# -ge 2 ]] || die "--file requires a path"; FILE="$2"; shift 2 ;; --yes) AUTO_YES=1; shift ;; -h|--help) echo "Usage: $(basename "$0") --file ARCHIVE [--yes]" exit 0 ;; *) die "Unknown option: $1" ;; esac done [[ -n "$FILE" ]] || die "Specify --file ARCHIVE" [[ -f "$FILE" ]] || die "Archive not found: $FILE" [[ -d "$SOURCE_DIR" ]] || die "Mounted Heimdall data volume is missing: $SOURCE_DIR" tar -tzf "$FILE" >/dev/null || die "Archive is invalid or truncated" while IFS= read -r member; do normalized="${member#./}" case "$normalized" in /*|..|../*|*/../*) die "Archive contains an unsafe path" ;; esac done < <(tar -tzf "$FILE") MEMBERS="$(tar -tzf "$FILE")" NORMALIZED_MEMBERS="$(sed 's#^\./##' <<<"$MEMBERS")" grep -q '^dp-keys/' <<<"$NORMALIZED_MEMBERS" \ || die "Archive does not contain the Data Protection key ring" if tar -tvzf "$FILE" | awk 'substr($0, 1, 1) == "l" || substr($0, 1, 1) == "h" { found = 1 } END { exit !found }'; then die "Archive contains a symbolic or hard link" fi if [[ "$AUTO_YES" != "1" ]]; then echo "This overlays local objects and the Data Protection key ring in: $SOURCE_DIR" echo "Stop Heimdall Central before restoring to avoid concurrent writes." read -rp "Type RESTORE to continue: " confirmation [[ "$confirmation" == "RESTORE" ]] || { log "Aborted"; exit 1; } fi RESTORE_DIR="$(mktemp -d /tmp/heimdall-protected-restore.XXXXXX)" trap 'rm -rf "$RESTORE_DIR"' EXIT tar -xzf "$FILE" -C "$RESTORE_DIR" --no-same-owner [[ -d "$RESTORE_DIR/dp-keys" ]] || die "Restored Data Protection key ring is missing" cp -a "$RESTORE_DIR/." "$SOURCE_DIR/" log "Protected data restored from $FILE" log "Existing target files not present in the archive were left unchanged"