aboutsummaryrefslogtreecommitdiff
path: root/local/bin/system-backup
blob: dfa2c090ba8334d31f33022cf17b31081b896f54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/bin/bash
# vim:ft=sh
# New line separated list of all directories to backup
DIRS="/etc
/home
/home_hdd"
# Name of the machine used in backup subvolumes
MNAME=asus
# Path where backup will be mounted
MPATH=/media/backup
# UUID of disk
UUID=b162ea95-38bb-42c6-b36a-1be98c65392c
# Mount additional arguments
MARGS="-o compress=lzo"
# If disk is encrypted
CRYPT=true
####################################################################
# Check if running as root
if [ `id -u` -ne "0" ]; then
	echo Please run this as root.
	exit 1
fi
set -e

# Mount disk
PART=$(lsblk -fpl | grep "$UUID" | awk '{print $1}')
if [ -z "$PART" ]; then
	echo Disk not detected. Exiting
	exit -1
fi
if $CRYPT; then
	echo -e "\e[1;33mDecrypting filesystem\e[0m"
	# TODO what if already opened
	cryptsetup open "$PART" backup || (echo Decryption failed && exit -2)
	PART=/dev/mapper/backup
	echo $PART
fi
echo -e "\e[1;33mMounting\e[0m"
mkdir -p "$MPATH"
mount $MARGS "$PART" "$MPATH" || (echo Mount failed && exit -3)

[ -d "$MPATH"/@"$MNAME" ] || (echo There seems to be no subvolume $MNAME && exit -4)

# Do backup
while read -r DIR; do
	echo -e "\e[1;33mBacking up: $DIR\e[0m"
	rsync -aAxXS --delete --progress "$DIR" "$MPATH"/@"$MNAME"/ || [ $? -eq 24 ]
	# We ignore exit code if rsync detects vanished source file
done <<< "$DIRS"

# Do snapshot (read only)
(cd "$MPATH"; btrfs subvolume snapshot -r @asus @asus-$(date -u +%y%m%d))

# Remove snapshots older than 2 months
# TODO ensure that at least five stays
(cd "$MPATH"
for s in @"$MNAME"-*; do
	if [ $(expr $(date +%s) - $(stat -c %Y "$s")) -gt 5529600 ]; then
		btrfs subvolume delete "$s"
	fi
done)

# Unmount disk
sync -f "$MPATH"/@"$MNAME"
umount "$MPATH" || (echo Unmount failed. Unmount by hand. && exit -5)
if $CRYPT; then
	cryptsetup close backup || (echo Encryption close failed. Do by hand. && exit -6)
fi

# Store when we did last backup and update i3blocks status
date +"%s" > /home/cynerd/.backup_date
pkill -RTMIN+13 i3blocks

echo
echo -e "\e[1;34mBackup finished\e[0m"