#!/bin/bash
# Usage: storage-rescue DEVICE OUTDIR
#   Copies the newest automatic backup and the newest hand-made one off a storage partition (ext4) that
#   can't be mounted, into OUTDIR. Run by mirrordash-hydrate.sh before it rebuilds the partition; prints
#   the names it saved. Exit 0 when at least one came out.
#
# debugfs -c (catastrophic mode) reads the file system without mounting it and without its block and inode
# bitmaps, the parts a broken one most often has wrong. With the first superblock gone it tries the
# copies ext4 keeps further on. ponytail: only the first five copies, at their places for 4 KiB blocks
# (mkfs.ext4's choice for every partition over 512 MB); upgrade path: read their places with dumpe2fs -o.
# Only the backups: with them the owner gets everything else back in one restore (ARCHITECTURE #58).
set -uo pipefail
dev=$1 out=$2
dir=/mirrordash/data/backups

for superblock in "" 32768 98304 163840 229376 294912; do
  opts=(-c)
  [ -n "$superblock" ] && opts+=(-s "$superblock" -b 4096)
  # ls -p: one /inode/mode/uid/gid/name/size/ line per entry
  listing=$(debugfs "${opts[@]}" -R "ls -p $dir" "$dev" 2>/dev/null | grep '^/') && [ -n "$listing" ] && break
done
[ -n "${listing:-}" ] || { echo "storage-rescue: no backups folder could be read" >&2; exit 1; }

# The names hold the time (YYYYmmdd_HHMMSS), so the last one sorted is the newest of each kind
newest() { awk -F/ -v prefix="$1" 'index($6, prefix) == 1 && $6 ~ /\.mirror$/ { print $6 "/" $7 }' <<< "$listing" | sort | tail -n 1; }
saved=0
for prefix in mirrordash_autobackup_ mirrordash_backup_; do
  entry=$(newest "$prefix")
  [ -n "$entry" ] || continue
  name=${entry%/*} size=${entry#*/}
  # A name in the listing comes from the broken disk: only a plain backup file name is used as a path
  [[ "$name" =~ ^[A-Za-z0-9_.-]+\.mirror$ ]] || continue
  debugfs "${opts[@]}" -R "dump $dir/$name $out/$name" "$dev" >/dev/null 2>&1
  # A file that didn't come out whole is worse than none: it would be offered for a restore
  if [ "$(stat -c %s "$out/$name" 2>/dev/null)" = "$size" ]; then
    echo "$name"
    saved=$((saved + 1))
  else
    rm -f "$out/$name"
    echo "storage-rescue: $name didn't come out whole" >&2
  fi
done
[ "$saved" -gt 0 ]
