|
#!/bin/sh |
|
# restore_root.sh |
|
# Host this script on a webserver so you can |
|
# fetch -o - http://192.168.1.2/restore_root.sh | sh |
|
|
|
# LiveCD-safe restore to latest snapshot made by backup script |
|
|
|
# Import the ZFS pool without mounting datasets |
|
echo "Importing pool '$POOL' without mounting datasets..." |
|
if zpool list "$POOL" >/dev/null 2>&1; then |
|
echo "Pool '$POOL' already imported. Attempting to export and re-import..." |
|
zpool export -f "$POOL" 2>/dev/null || { echo "Error: Failed to export pool '$POOL'."; exit 1; } |
|
fi |
|
if ! zpool import -N "$POOL"; then |
|
echo "Error: Failed to import pool '$POOL'. Retrying with force..." |
|
zpool import -f -N "$POOL" || { echo "Error: Failed to import pool '$POOL' after retry."; exit 1; } |
|
fi |
|
|
|
# Find the latest snapshot with the specified prefix |
|
SNAP_NAME=$(zfs list -t snapshot -H -o name -s creation | grep "^${POOL}@${PREFIX}-" | tail -n 1) |
|
if [ -z "$SNAP_NAME" ]; then |
|
echo "Error: No snapshots found on '$POOL' with prefix '$PREFIX'." |
|
exit 1 |
|
fi |
|
echo "Latest snapshot: $SNAP_NAME" |
|
|
|
# Detect the active root dataset |
|
ROOT_DS=$(zfs list -H -o name | grep "^${POOL}/ROOT/" | head -n 1) |
|
if [ -z "$ROOT_DS" ]; then |
|
echo "Error: No active root dataset found under '$POOL/ROOT'." |
|
exit 1 |
|
fi |
|
echo "Active root dataset: $ROOT_DS" |
|
|
|
# Check for newer snapshots that might prevent rollback |
|
NEWER_SNAPS=$(zfs list -t snapshot -H -o name -s creation | grep "^${ROOT_DS}@" | awk -v snap="$SNAP_NAME" '$0 > snap') |
|
if [ -n "$NEWER_SNAPS" ]; then |
|
echo "Error: Newer snapshots exist, which will be destroyed by rollback:" |
|
echo "$NEWER_SNAPS" | awk '{ print " -", $0 }' |
|
echo "Type 'yes' to confirm destructive rollback:" |
|
read -r CONFIRM |
|
if [ "$CONFIRM" != "yes" ]; then |
|
echo "Rollback cancelled." |
|
exit 1 |
|
fi |
|
fi |
|
|
|
# Perform the rollback |
|
echo "Rolling back '$ROOT_DS' to snapshot '$SNAP_NAME'..." |
|
if ! zfs rollback -r "$SNAP_NAME"; then |
|
echo "Error: Rollback failed." |
|
exit 1 |
|
fi |
|
|
|
echo "Rollback complete. Pool will be exported automatically." |
|
echo "Reboot the system to boot into the restored filesystem:" |
|
echo " reboot" |
|
echo "Remove the Live CD/ISO after reboot." |