dotfiles/root/usr/local/bin/incremental-backup

56 lines
2 KiB
Plaintext
Raw Normal View History

2022-11-19 21:20:56 +00:00
#!/bin/bash
# Script to perform incremental backups using rsync
# It is often ran as crontab rule for automated backup solution
#
# This script will respect .rsync-filter files, which can be used
# to define custom exclude rules for files/dirs in which it is present
if [ $# -lt 2 ]; then
2023-11-18 23:12:13 +00:00
echo "Invalid amount of arguments passed!"
echo "Arguments: <Source path> <Backup path> [--note]"
echo " <Source path>: directory to be backed up, usually '/'"
echo " <Backup path>: directory to back up to (destination), usually mounted drive"
exit
2022-11-19 21:20:56 +00:00
fi
SOURCE_DIR="$1"
BACKUP_DIR="$2"
DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
LATEST_LINK="${BACKUP_DIR}/latest"
2023-11-18 23:12:13 +00:00
NOTE_FILE="${BACKUP_PATH}/note.md"
2022-11-19 21:20:56 +00:00
mkdir -p "$BACKUP_DIR"
rsync -avHAXS \
2023-11-18 23:12:13 +00:00
--delete \
--filter='dir-merge /.rsync-filter' \
--link-dest "${LATEST_LINK}" \
"${@:3}" "${SOURCE_DIR}/" "${BACKUP_PATH}"
2022-11-19 21:20:56 +00:00
# Only attempt to override the symlink if we made new backup_path
# user might've passed --dry-run option in which case we wouldn't
# want to override latest symlink to non-existent location
if [ -d "${BACKUP_PATH}" ]; then
2023-11-18 23:12:13 +00:00
rm "${LATEST_LINK}" 2>/dev/null
ln -s "$(basename "$BACKUP_PATH")" "${LATEST_LINK}"
fi
# Lastly, open a note file with $EDITOR insite of the backup dir,
# so the user can put in any personal notes about this backup (such
# as reason it was made, making it easy to identify it).
#
# If this command is ran with sudo (like for system wide backups),
# open the note file with user's editor, not root's
if [ "${SUDO_USER:-$USER}" != "$USER" ]; then
# Run command as the original user via sudo, with -s argument, to
# also load the user's shell, so the user's env variables ($EDITOR)
# gets set. Then make the user run sudoedit, opening a temp file,
# which when saved, will get written to the note file as user we're
# sudoed as. Note: this will re-prompt for sudo password.
NOTE_FILE="$NOTE_FILE" sudo -s --preserve-env="NOTE_FILE" -u "$SUDO_USER" sh -c 'sudoedit -u "$SUDO_USER" "$NOTE_FILE"'
else
$EDITOR "$NOTE_FILE"
2022-11-19 21:20:56 +00:00
fi