Add backup script

Signed-off-by: Nikolaos Karaolidis <nick@karaolidis.com>
This commit is contained in:
2025-01-12 13:20:31 +00:00
parent fca554dbd4
commit 8e18ca20a9
12 changed files with 160 additions and 51 deletions

View File

@@ -0,0 +1,16 @@
_backup_completion() {
local options=(
'-m[specify partition to mount for backup]:partition:($(_partitions))'
'-b[specify backup directory]:backup directory:_files -/'
)
local curcontext="$curcontext" state line
typeset -A opt_args
_partitions() {
lsblk -rno NAME | sed 's/^/\/dev\//'
}
_arguments -s $options
}
compdef _backup_completion backup

View File

@@ -0,0 +1,64 @@
if [[ "${EUID}" -ne 0 ]]; then
echo "Please run the script as root."
exit 1
fi
usage() {
echo "Usage: $0 [-m partition] [-b backup_location]"
exit 1
}
cleanup() {
if [ -d "/persist.bak" ]; then btrfs -q subvolume delete "/persist.bak"; fi
if [ -n "${backup_location}" ] && [ -f "${backup_location}.tmp" ]; then rm "${backup_location}.tmp"; fi
if [ -n "${mount_location}" ]; then
if mount | grep -q "${mount_location}"; then umount "${mount_location}"; fi
if [ -d "${mount_location}" ]; then rmdir "${mount_location}"; fi
fi
}
partition=""
backup_location=""
mount_location=""
trap cleanup EXIT
while getopts "m:b:" opt; do
case "${opt}" in
m) partition="${OPTARG}" ;;
b) backup_location="${OPTARG}" ;;
*) usage ;;
esac
done
if [ -n "${partition}" ]; then
mount_location=$(mktemp -d /mnt/backup.XXXXXX)
echo "Mounting ${partition} at ${mount_location}..."
mount "${partition}" "${mount_location}"
fi
if [ -z "${mount_location}" ]; then
if [[ "${backup_location}" != /* ]]; then
backup_location="$(realpath "${backup_location}")"
fi
else
if [[ "${backup_location}" = /* ]]; then
echo "Error: When a partition is mounted, backup_location must be relative."
exit 1
fi
backup_location="$(realpath "${mount_location}/${backup_location}")"
fi
backup_location="${backup_location}/$(hostname)-$(date +%Y-%m-%d-%H-%M-%S).btrfs.gz"
echo "Creating /persist snapshot..."
btrfs -q subvolume snapshot -r "/persist" "/persist.bak"
echo "Creating backup at ${backup_location}..."
btrfs -q send "/persist.bak" | gzip > "${backup_location}.tmp"
mv "${backup_location}.tmp" "${backup_location}"
echo "Backup completed successfully!"

View File

@@ -0,0 +1,20 @@
{ pkgs, ... }:
{
environment.systemPackages = [
(pkgs.writeShellApplication {
name = "backup";
runtimeInputs = with pkgs; [
btrfs-progs
coreutils-full
util-linux
];
text = builtins.readFile ./backup.sh;
})
];
home-manager.sharedModules = [
{
programs.zsh.initExtra = builtins.readFile ./backup.completion.zsh;
}
];
}