Last active
April 12, 2020 09:29
-
-
Save yann2192/267e310c91ffca44a04a to your computer and use it in GitHub Desktop.
Incremental backup using btrfs snapshot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
DEVICE=UUID="2b387045-9c35-4da0-8ed2-79014eb85040" | |
BACKUP_DEVICE="dde" | |
BACKUP_MOUNT="/mnt" | |
DEST="$BACKUP_MOUNT/backup" | |
MAX_BACKUPS=20 | |
SOURCE="/home/yann" | |
SNAP_DIR="/home/backup" | |
_mount() { | |
cryptsetup luksOpen "$DEVICE" "$BACKUP_DEVICE" | |
mount "/dev/mapper/$BACKUP_DEVICE" "$BACKUP_MOUNT" | |
} | |
_umount() { | |
sync | |
umount "/dev/mapper/$BACKUP_DEVICE" | |
cryptsetup luksClose "$BACKUP_DEVICE" | |
} | |
_backup() { | |
latest="$(btrfs subvolume list -ors --sort=gen "$SNAP_DIR" | rev | cut -d"/" -f1 | rev | tail -1)" | |
if [[ -z "$latest" ]]; then | |
date=$(date "+%Y-%m-%dT%H:%M:%S") | |
latest="$date-$(uuidgen)" | |
btrfs subvolume snapshot -r "$SOURCE" "$SNAP_DIR/$latest" | |
btrfs send "$SNAP_DIR/$latest" | btrfs receive "$DEST/" | |
else | |
date=$(date "+%Y-%m-%dT%H:%M:%S") | |
new_latest="$date-$(uuidgen)" | |
btrfs subvolume snapshot -r "$SOURCE" "$SNAP_DIR/$new_latest" | |
btrfs send -p "$SNAP_DIR/$latest" "$SNAP_DIR/$new_latest" | btrfs receive "$DEST/" | |
fi | |
} | |
_clean() { | |
todelete="$(btrfs subvolume list -ors --sort=gen "$SNAP_DIR" | rev | cut -d"/" -f1 | rev | head -n -$MAX_BACKUPS)" | |
for vol in $todelete; do | |
btrfs subvolume delete "$SNAP_DIR/$vol"; | |
done | |
todelete="$(btrfs subvolume list -ors --sort=gen "$DEST" | rev | cut -d"/" -f1 | rev | head -n -$MAX_BACKUPS)" | |
for vol in $todelete; do | |
btrfs subvolume delete "$DEST/$vol"; | |
done | |
} | |
_get() { | |
local_latest="$(btrfs subvolume list -ors --sort=gen "$SNAP_DIR" | rev | cut -d"/" -f1 | rev | tail -1)" | |
echo "Local last: $local_latest" | |
latest="$(btrfs subvolume list -ors --sort=gen "$DEST" | rev | cut -d"/" -f1 | rev | tail -1)" | |
echo "Last: $latest" | |
# retrieve backup | |
btrfs send -p "$DEST/$local_latest" "$DEST/$latest" | btrfs receive "$SNAP_DIR/" | |
# custom | |
umount /home/yann/.cache | |
# Apply backup on $SOURCE | |
btrfs subvolume delete "$SOURCE" | |
btrfs subvolume snapshot "$SNAP_DIR/$latest" "$SOURCE" | |
# custom | |
mount -a | |
} | |
case "$1" in | |
mount) shift; _mount "$@" ;; | |
umount) shift; _umount "$@" ;; | |
backup) shift; _backup "$@" ;; | |
clean) shift; _clean "$@" ;; | |
get) shift; _get "$@" ;; | |
esac | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment