Skip to content

Instantly share code, notes, and snippets.

@martin-v
Last active January 17, 2023 10:20
Show Gist options
  • Save martin-v/b79a77a21134de0e22ee5299bb19a9c9 to your computer and use it in GitHub Desktop.
Save martin-v/b79a77a21134de0e22ee5299bb19a9c9 to your computer and use it in GitHub Desktop.
Notebook backup script for fedora/rhel using borg
#!/usr/bin/env bash
set -o nounset
set -o errexit
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace; fi
if [[ "${1-}" =~ ^-+h(elp)?$ ]]; then
cat << USAGE
Usage: ./$(basename "$0")
Backup this pc to a borg repository (https://www.borgbackup.org/). Handles pruning and desktop notifications.
Only starts a backup if there is enough power and the wifi is whitelisted.
USAGE
exit
fi
REPOSITORY="ssh://...."
VALID_WIFIS="Wifi1 Wifi2"
USERID=1000
LOG="/root/backup.log"
DATE="$(date -I)"
# Output to a logfile
exec > >(tee -a -i "$LOG")
exec 2>&1
# send desktop
BACKUP_MSG_ID=0
function msg() {
BACKUP_MSG_ID="$(
sudo -u "#$USERID" DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$USERID/bus" \
notify-send \
--app-name=backup \
--icon=drive-multidisk \
--print-id \
--replace-id="$BACKUP_MSG_ID" \
"Backup $1" "$2 $DATE"
)"
}
echo "###### Check conditions ######"
[ "$(cat /sys/class/power_supply/AC/online)" -eq "1" ] || ( msg "failed" "no AC" ; exit 5 )
[ "$(cat /sys/class/power_supply/BAT0/capacity)" -gt "50" ] || ( msg "failed" "Bat not full enough" ; exit 6 )
curr_wifi="$(nmcli connection show --active | grep wifi | awk '{print $1}')"
[[ "$VALID_WIFIS" =~ ( |^)$curr_wifi( |$) ]] || ( msg "failed" "Unknown wifi '$curr_wifi'" ; exit 7 )
msg "started ..." ""
# collecting system logs and other debug information
rm -f /root/sos-report/*
sos report --batch -n sendmail --tmp-dir /root/sos-report
echo "###### Backup started: $DATE ######"
# --dry-run --list \
borg create \
--remote-path "borg-$(borg --version | cut -c6-8)" \
--verbose \
--stats \
--progress \
--compression auto,zstd \
--patterns-from /root/borg-pattern \
"$REPOSITORY"::"${DATE}" \
/home \
/root \
/etc \
msg "done" "cleaning up now"
borg prune \
--remote-path "borg-$(borg --version | cut -c6-8)" \
--verbose \
--stats \
--progress \
--list \
--keep-within 2d \
--keep-daily 10 \
--keep-weekly 4 \
--keep-monthly 12 \
"$REPOSITORY" \
borg compact \
--remote-path "borg-$(borg --version | cut -c6-8)" \
--verbose \
--progress \
"$REPOSITORY" \
msg "done" "cleaning complete"
echo "###### Backup ended: $DATE ######"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment