BTRFS snapshot to help with rclone

A script that might be helpful for someone looking to leverage BTRFS's copy on write/snapshot capabilities to provide a stable input for rclone. Depending on your subvolume layout you may need to tweak the script as well; should work as is if Timeshift set up the subvolumes for you.

btw the saved-permissions file gets injected into /current in case you need to recover the permissions later; its got nothing to do with using a BTRFS snapshot

Use at your own risk and make sure you know what the sudo commands are doing!!

#!/bin/bash
#
# Copies all non-excluded files from @home/$USER, using sync w/ backup-dir to keep old files
#
# WARNING: sudo is used
#
# This script requires/hardcoded a /bin inside the user home as well as a premade mnt/backup/ folder inside it
# save-permissions in /home/$user/bin can be used to reconstruct the permissions programatically or just eyeballed direct
#
# This script has no error checking atm... confirm before running that it does not clobber your files
#
# 

temp_mount_location='/home/'$USER'/bin/mnt/backup'
drive_device='/dev/nvmeX_or_sdY'
remote1_location="HDD:/rclone_backups/"

echo 'Script: creating and mounting snapshot'
sudo btrfs subvol snapshot /home /temp_snapshot
sudo mount -t btrfs -o subvol=@/temp_snapshot $drive_device $temp_mount_location

echo 'Script: preserve permissions of snapshot files'
find $temp_mount_location'/' -depth -printf '%m:%u:%g:%p\n' > $temp_mount_location/$USER/bin/saved-permissions
sudo btrfs filesystem sync /temp_snapshot 

echo 'Script: transferring data in snapshot'
rclone sync \
    $temp_mount_location/$USER $remote1_location"current" \
    --backup-dir $remote1_location$(date +"%d-%m-%yT%H%M%S") \
    --metadata \
    --links \
    --fast-list \
    --exclude "/Downloads/**" \
    --exclude "/.cache/**" \
    --exclude "/.~lock**" \
    --exclude "/.local/share/Trash/**"\
    --progress

echo 'Script: cleanup'
# Delete snapshot now we're done and unmount
sudo btrfs subvol delete --commit-after /temp_snapshot
sudo umount $temp_mount_location

echo 'Script: done'