4 REMOTE_BASE=/tmp/backmeupscotty
5 ARCHIVE_KEEPNBACKUPS=30
7 BACKUP_RUNEVERYNTHDAY=1
10 echo $(basename $0) | tr '[:lower:]' '[:upper:]'
17 function scottyerror {
18 echo $(upperme): $@ >&2
21 if [ $(pidof -x $(basename $0) | wc -w) -gt 2 ]; then
22 scottyerror Another instance of $(basename $0) is already running!
26 while getopts "qn:" opt; do
32 BACKUP_RUNEVERYNTHDAY=$OPTARG
37 function grepbackups {
38 ssh $REMOTE_HOST "ls $REMOTE_BASE/$1" | grep -E '[0-9]+-[0-9]+'
41 function isIncomplete {
42 if ( ssh $REMOTE_HOST '[ -d '$REMOTE_BASE/$1/incomplete' ]' ); then
49 function isIncompleteOrNthDay {
50 if isIncomplete $1 || \
51 [ $(( ( $(date +%s) / (60*60*24) ) % $BACKUP_RUNEVERYNTHDAY )) -eq 0 ];
63 scottyinfo Syncing $1 to $REMOTE_HOST:$REMOTE_BASE/$2 @$timestamp
65 if [ ! -d "$1" ]; then
66 scottyerror Source dir $1 does not exist. Not syncing!
70 if [ $(ls -A "$1" | wc -l) -eq 0 ]; then
71 scottyerror Source dir $1 is empty. Not syncing!
75 dir_current=$REMOTE_BASE/$2/current
76 dir_incomplete=$REMOTE_BASE/$2/incomplete
77 dir_timestamped=$REMOTE_BASE/$2/$timestamp-$(date -d @$timestamp +%Y%m%d%H%M%S)
82 rsync_exclude=$(eval echo --exclude={$3} | tr -d {})
85 if (ssh $REMOTE_HOST '[ ! -d '$REMOTE_BASE/$2' ]'); then
86 scottyinfo Creating destination directory $REMOTE_HOST:$REMOTE_BASE/$2
87 ssh $REMOTE_HOST "mkdir $REMOTE_BASE/$2"
90 if isIncomplete $2; then
91 scottyerror Continuing old incomplete backup
94 scottyinfo Starting rsync
96 -v -aHAX --numeric-ids --delete --delete-excluded \
97 --link-dest=$dir_current \
99 $1/ $REMOTE_HOST:$dir_incomplete/
101 if [ $? -eq 0 ]; then
102 scottyinfo Timestamping completed backup and linking to current backup
104 "mv $dir_incomplete $dir_timestamped && rm -f $dir_current && ln -s $(basename $dir_timestamped) $dir_current"
107 while [ $(grepbackups $2 | wc -l) -gt $ARCHIVE_KEEPNBACKUPS ]; do
108 oldestbackup=$(grepbackups $2 | head -1)
109 oldestbackuptstamp=$(echo $oldestbackup | cut -d'-' -f1)
111 if [ $oldestbackuptstamp -lt $(( $(date +%s) - $ARCHIVE_KEEPNDAYS*60*60*24 )) ]; then
112 scottyinfo Removing old backup $oldestbackup
113 ssh $REMOTE_HOST rm -r "$REMOTE_BASE/$2/$oldestbackup"