]> git.treefish.org Git - backmeupscotty.git/blob - backmeupscotty
e9bab430abb4c03726c44a4338255499d266a000
[backmeupscotty.git] / backmeupscotty
1 #!/bin/bash
2
3 REMOTE_HOST=localhost
4 REMOTE_BASE=/tmp/backmeupscotty
5 ARCHIVE_KEEPNBACKUPS=30
6 ARCHIVE_KEEPNDAYS=30
7
8 if [ $(pidof -x $(basename $0) | wc -w) -gt 2 ]; then 
9     echo BACKMEUPSCOTTY: Another instance of $(basename $0) is already running! >&2
10     exit 1
11 fi
12
13 while getopts ":q" opt; do
14     case $opt in
15         q)
16             exec > /dev/null
17             ;;
18     esac
19 done
20
21 function grepbackups {
22     ssh $REMOTE_HOST "ls $REMOTE_BASE/$1" | grep -E '[0-9]+-[0-9]+'
23 }
24
25 function scottysync {
26     timestamp=$(date +%s)
27
28     echo BACKMEUPSCOTTY: Syncing $1 to $REMOTE_HOST:$REMOTE_BASE/$2 @$timestamp
29
30     if [ ! -d "$1" ]; then
31         echo BACKMEUPSCOTTY: Source dir $1 does not exist. Not syncing! >&2
32         return 1
33     fi
34
35     if [ $(ls -A "$1" | wc -l) -eq 0 ]; then
36         echo BACKMEUPSCOTTY: Source dir $1 is empty. Not syncing! >&2
37         return 1
38     fi
39
40     dir_current=$REMOTE_BASE/$2/current
41     dir_incomplete=$REMOTE_BASE/$2/incomplete
42     dir_timestamped=$REMOTE_BASE/$2/$timestamp-$(date -d @$timestamp +%Y%m%d%H%M%S)
43
44     if [ -z $3 ]; then
45         rsync_exclude=""
46     else
47         rsync_exclude=$(eval echo --exclude={$3} | tr -d {})
48     fi
49
50     if (ssh $REMOTE_HOST '[ ! -d '$REMOTE_BASE/$2' ]'); then
51         echo BACKMEUPSCOTTY: Creating destination directory $REMOTE_HOST:$REMOTE_BASE/$2
52         ssh $REMOTE_HOST "mkdir $REMOTE_BASE/$2"
53     fi
54
55     if (ssh $REMOTE_HOST '[ -d '$REMOTE_BASE/$2/incomplete' ]'); then
56         echo BACKMEUPSCOTTY: Continuing old incomplete backup >&2
57     fi
58
59     echo BACKMEUPSCOTTY: Starting rsync
60     rsync -e ssh \
61         -v -aHAX --numeric-ids --delete --delete-excluded \
62         --link-dest=$dir_current \
63         $rsync_exclude \
64         $1/ $REMOTE_HOST:$dir_incomplete/
65     
66     if [ $? -eq 0 ]; then
67         echo BACKMEUPSCOTTY: Timestamping completed backup and linking to current backup
68         ssh $REMOTE_HOST \
69             "mv $dir_incomplete $dir_timestamped && rm -f $dir_current && ln -s $dir_timestamped $dir_current"
70     fi
71
72     while [ $(grepbackups $2 | wc -l) -gt $ARCHIVE_KEEPNBACKUPS ]; do
73         oldestbackup=$(grepbackups $2 | head -1)
74         oldestbackuptstamp=$(echo $oldestbackup | cut -d'-' -f1)
75
76         if [ $oldestbackuptstamp -lt $(( $(date +%s) - $ARCHIVE_KEEPNDAYS*60*60*24 )) ]; then
77             echo BACKMEUPSCOTTY: Removing old backup $oldestbackup
78             ssh $REMOTE_HOST rm -r "$REMOTE_BASE/$2/$oldestbackup"
79         else
80             break
81         fi
82     done
83 }