116 lines
2.6 KiB
Bash
Executable file
116 lines
2.6 KiB
Bash
Executable file
#!/bin/bash
|
|
|
|
# dir to backup
|
|
|
|
cd $(dirname $0)
|
|
|
|
usage() {
|
|
echo "backup script with snapshots"
|
|
echo "$0 [-x exclude dir] [-k N] <backup dir>"
|
|
echo
|
|
echo " -x excludes sub directory"
|
|
echo " -k defines how many snapshots to keep (default 7)"
|
|
echo " -q supress verbose output"
|
|
echo
|
|
}
|
|
|
|
# read configuration variables
|
|
source config.sh
|
|
|
|
BDIR=""
|
|
EXCLUDE=""
|
|
|
|
#### READ PARAMETERS
|
|
|
|
while getopts ":x:hqk:" opt; do
|
|
case $opt in
|
|
x)
|
|
EXCLUDE="${EXCLUDE} --exclude ${SNAPSHOTDIR}/${OPTARG}"
|
|
;;
|
|
h)
|
|
usage
|
|
exit 0
|
|
;;
|
|
q)
|
|
QUIET="--quiet"
|
|
;;
|
|
k)
|
|
KEEPLAST="${OPTARG}"
|
|
;;
|
|
\?)
|
|
echo "ERROR: Invalid option: -$OPTARG" >&2
|
|
usage
|
|
exit 1
|
|
;;
|
|
:)
|
|
echo "ERROR: Option -$OPTARG requires an argument." >&2
|
|
usage
|
|
exit 1
|
|
;;
|
|
esac
|
|
done
|
|
shift $((OPTIND-1))
|
|
|
|
BDIR=${1}
|
|
|
|
if [ -z "$BDIR" ]; then
|
|
echo "ERROR: Missing backup directory!" >&2
|
|
usage
|
|
exit 2
|
|
fi
|
|
|
|
#### END READ PARAMETERS
|
|
|
|
# umount and close everything if it is mounted before
|
|
uuid=$(cat /proc/sys/kernel/random/uuid)
|
|
|
|
if ! ./lock.sh haslock; then
|
|
echo "###" BEGIN EXPECTED ERRORS >&2
|
|
umount -v $SNAPSHOTDIR
|
|
cryptsetup close snapshot-decrypt
|
|
lvremove -f vg01/crypt-snapshot
|
|
echo "###" END EXPECTED ERRORS >&2
|
|
|
|
mkdir -p $SNAPSHOTDIR
|
|
|
|
# create snapshot of data volume
|
|
sync
|
|
lvcreate -l100%FREE -s -n crypt-snapshot /dev/vg01/data-crypt || exit 1
|
|
|
|
# decrypt snapshot with key on unencrypted partition
|
|
echo mounting snapshot
|
|
cryptsetup open --type luks --key-file /data/_lukskeyfile /dev/vg01/crypt-snapshot snapshot-decrypt || exit 2
|
|
|
|
# mount the freshly decrypted backup
|
|
mount -o ro /dev/mapper/snapshot-decrypt $SNAPSHOTDIR || exit 3
|
|
fi
|
|
|
|
./lock.sh lock $uuid
|
|
|
|
export RESTIC_PASSWORD=${BACKUP_PASSWORD}
|
|
|
|
SNAPSHOTPATH=$SNAPSHOTDIR
|
|
if [[ -n "$BDIR" && "$BDIR" != "." ]]; then
|
|
SNAPSHOTPATH=$SNAPSHOTDIR/$BDIR
|
|
fi
|
|
|
|
echo "Backup path: $SNAPSHOTPATH"
|
|
# backup the snapshot (without freezing the filesystem)
|
|
# use -q for quiet mode (when run as a cron job)
|
|
ionice -c 3 $RESTIC --repo $URI $EXCLUDE $QUIET backup "$SNAPSHOTPATH"
|
|
|
|
./lock.sh unlock $uuid
|
|
|
|
if ! ./lock.sh haslock; then
|
|
# at this point we no longer need the snapshot and can unmount it
|
|
umount $SNAPSHOTDIR
|
|
cryptsetup close snapshot-decrypt
|
|
lvremove -f vg01/crypt-snapshot
|
|
fi
|
|
|
|
# delete everything older than the last X snapshots
|
|
$RESTIC --repo $URI $QUIET forget --keep-last $KEEPLAST --path "$SNAPSHOTPATH"
|
|
|
|
unset RESTIC_PASSWORD
|
|
|
|
exit 0
|