#!/bin/bash BORGUSER="{{ backup_owner }}"; RUNFOLDER="{{ backup_run_folder }}"; TARGETFOLDER="{{ backup_storage }}"; REPOLOCATION="{{ backup_location }}"; ARCHIVENAME="{{ backup_app }}-$(date '+%s')"; help (){ echo "cloud_backup - backup and restore script on cloud with borg target v1.0 by L.Hahn. Usage: $0 COMMAND [ARCHIVENAME] COMMAND: - list List available archives in remote borg repository for your host. - backup Perform backup of your host and create a new archive in borg repository. - restore [ARCHIVENAME] Download backup from borg repository to your host and restore files. May turn off your application if still running. If no ARCHIVENAME is provided, the latest one based on timestamp is taken. IF ARCHIVENAME is provided, will try to download it; throws error if not found. "; } ### INDIVIDUAL TEMPLATE PART ### prework_backup () { {{ backup_script.prework_backup | indent( width=4) }} } postwork_restore () { {{ backup_script.postwork_restore | indent( width=4) }} } ### SHARED TEMPLATE PART ### get_archives () { ARCHIVEIDS=$( sudo -H -u $BORGUSER bash -c ' REPOLOCATION='$REPOLOCATION'; export BORG_PASSPHRASE=$(cat {{ backup_home }}/.borg.key); borg list $REPOLOCATION' | sort -r); echo "$ARCHIVEIDS"; } cloud_backup () { mkdir -p $TARGETFOLDER/$ARCHIVENAME; prework_backup; cd /; sudo -H -u $BORGUSER bash -c ' TARGETFOLDER='$TARGETFOLDER'; REPOLOCATION='$REPOLOCATION'; ARCHIVENAME='$ARCHIVENAME'; export BORG_PASSPHRASE=$(cat {{ backup_home }}/.borg.key); borg create -C lzma $REPOLOCATION::$ARCHIVENAME $TARGETFOLDER/$ARCHIVENAME'; rm -rf $TARGETFOLDER/$ARCHIVENAME; } cloud_restore () { ARCHIVENAME=$1; ARCHIVEIDS=$(get_archives | cut -f 1 -d ' '); if [[ "${ARCHIVENAME,,}" == "latest" ]]; then ARCHIVENAME=$(echo "$ARCHIVEIDS" | head -n 1); else if [[ "$ARCHIVEIDS" != *ARCHIVENAME* ]]; then echo "ERROR! Provided archivename $ARCHIVENAME is not part of the available archives! Aborting."; exit 1; fi fi mkdir -p $TARGETFOLDER/$ARCHIVENAME; chown -R $BORGUSER: $TARGETFOLDER cd /; sudo -H -u $BORGUSER bash -c ' REPOLOCATION='$REPOLOCATION'; ARCHIVENAME='$ARCHIVENAME'; export BORG_PASSPHRASE=$(cat {{ backup_home }}/.borg.key); borg extract $REPOLOCATION::$ARCHIVENAME --list'; postwork_restore; rm -rf $TARGETFOLDER/$ARCHIVENAME; } ( flock -n 9 || { echo "BACKUP ALREADY RUNNING! ABORTING."; exit 1; } if [ $# = 0 ]; then help; exit 0; fi action=$1 case $action in "list") get_archives; ;; "backup") cloud_backup; ;; "restore") cloud_restore $2; ;; *) help; ;; esac echo "" ) 9>/var/run/lock/cloud-backup.lock;