]> git.treefish.org Git - backmeupscotty.git/blob - backmeupscotty
Exit if another instance is already running
[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     dir_current=$REMOTE_BASE/$2/current
31     dir_incomplete=$REMOTE_BASE/$2/incomplete
32     dir_timestamped=$REMOTE_BASE/$2/$timestamp-$(date -d @$timestamp +%Y%m%d%H%M%S)
33
34     if [ -z $3 ]; then
35         rsync_exclude=""
36     else
37         rsync_exclude=$(eval echo --exclude={$3} | tr -d {})
38     fi
39
40     if (ssh $REMOTE_HOST '[ ! -d '$REMOTE_BASE/$2' ]'); then
41         echo BACKMEUPSCOTTY: Creating destination directory $REMOTE_HOST:$REMOTE_BASE/$2
42         ssh $REMOTE_HOST "mkdir $REMOTE_BASE/$2"
43     fi
44
45     if (ssh $REMOTE_HOST '[ -d '$REMOTE_BASE/$2/incomplete' ]'); then
46         echo BACKMEUPSCOTTY: Continuing old incomplete backup >&2
47     fi
48
49     echo BACKMEUPSCOTTY: Starting rsync
50     rsync -e ssh \
51         -v -aHAX --numeric-ids --delete --delete-excluded \
52         --link-dest=$dir_current \
53         $rsync_exclude \
54         $1/ $REMOTE_HOST:$dir_incomplete/
55     
56     if [ $? -eq 0 ]; then
57         echo BACKMEUPSCOTTY: Timestamping completed backup and linking to current backup
58         ssh $REMOTE_HOST \
59             "mv $dir_incomplete $dir_timestamped && rm -f $dir_current && ln -s $dir_timestamped $dir_current"
60     fi
61
62     while [ $(grepbackups $2 | wc -l) -gt $ARCHIVE_KEEPNBACKUPS ]; do
63         oldestbackup=$(grepbackups $2 | head -1)
64         oldestbackuptstamp=$(echo $oldestbackup | cut -d'-' -f1)
65
66         if [ $oldestbackuptstamp -lt $(( $(date +%s) - $ARCHIVE_KEEPNDAYS*60*60*24 )) ]; then
67             echo BACKMEUPSCOTTY: Removing old backup $oldestbackup
68             ssh $REMOTE_HOST rm -r "$REMOTE_BASE/$2/$oldestbackup"
69         else
70             break
71         fi
72     done
73 }