]> git.treefish.org Git - backmeupscotty.git/blob - backmeupscotty
d1500c1c3d15d7bce4384d9fbd23e033a2cc2f5c
[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 while getopts ":q" opt; do
9     case $opt in
10         q)
11             exec > /dev/null
12             ;;
13     esac
14 done
15
16 function grepbackups {
17     ssh $REMOTE_HOST "ls $REMOTE_BASE/$1" | grep -E '[0-9]+-[0-9]+'
18 }
19
20 function scottysync {
21     timestamp=$(date +%s)
22
23     echo BACKMEUPSCOTTY: Syncing $1 to $REMOTE_HOST:$REMOTE_BASE/$2 @$timestamp
24
25     dir_current=$REMOTE_BASE/$2/current
26     dir_incomplete=$REMOTE_BASE/$2/incomplete
27     dir_timestamped=$REMOTE_BASE/$2/$timestamp-$(date -d @$timestamp +%Y%m%d%H%M%S)
28
29     if [ -z $3 ]; then
30         rsync_exclude=""
31     else
32         rsync_exclude=$(eval echo --exclude={$3} | tr -d {})
33     fi
34
35     if (ssh $REMOTE_HOST '[ ! -d '$REMOTE_BASE/$2' ]'); then
36         echo BACKMEUPSCOTTY: Creating destination directory $REMOTE_HOST:$REMOTE_BASE/$2
37         ssh $REMOTE_HOST "mkdir $REMOTE_BASE/$2"
38     fi
39
40     if (ssh $REMOTE_HOST '[ -d '$REMOTE_BASE/$2/incomplete' ]'); then
41         echo BACKMEUPSCOTTY: Continuing old incomplete backup >&2
42     fi
43
44     echo BACKMEUPSCOTTY: Starting rsync
45     rsync -e ssh \
46         -v -aHAX --numeric-ids --delete --delete-excluded \
47         --link-dest=$dir_current \
48         $rsync_exclude \
49         $1/ $REMOTE_HOST:$dir_incomplete/
50     
51     if [ $? -eq 0 ]; then
52         echo BACKMEUPSCOTTY: Timestamping completed backup and linking to current backup
53         ssh $REMOTE_HOST \
54             "mv $dir_incomplete $dir_timestamped && rm -f $dir_current && ln -s $dir_timestamped $dir_current"
55     fi
56
57     while [ $(grepbackups $2 | wc -l) -gt $ARCHIVE_KEEPNBACKUPS ]; do
58         oldestbackup=$(grepbackups $2 | head -1)
59         oldestbackuptstamp=$(echo $oldestbackup | cut -d'-' -f1)
60
61         if [ $oldestbackuptstamp -lt $(( $(date +%s) - $ARCHIVE_KEEPNDAYS*60*60*24 )) ]; then
62             echo BACKMEUPSCOTTY: Removing old backup $oldestbackup
63             ssh $REMOTE_HOST rm -r "$REMOTE_BASE/$2/$oldestbackup"
64         else
65             break
66         fi
67     done
68 }