Friday 13 July 2012

Arcade Otaku's backup script

This takes advantage of Debian's /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly folders to automate backups with a single script, no editing of the stock crontab is necessary.

We only backup the forum (phpBB3) and wiki (Mediawiki) databases but those commands can be repeated for whatever you require.

Thanks to InvZim (http://www.kirurg.org) and stackoverflow.com for some bits.

#! /bin/bash

### System Setup
NOW="$(date +%Y%m%d-%H%M)"
DIRS="/home /root /etc /var/www"
BACKUP="/tmp/backup.$$"
NICE="ionice -c 3 nice -n 19"
RSYNC="$(which rsync)"
REMOTE="sanitised.backup.location.com::backups/"

### MySQL Setup
DBUSER=root
DBPASS=MYSQLROOTPASSWORD
DBHOST=localhost
DBBACKUP="$BACKUP/mysql"
MYSQLDUMP="$(which mysqldump)"
MYSQLHOTCOPY="$(which mysqlhotcopy)"

### Stolen from stackoverflow.com question #59895
### Returns the directory the script is running in
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

### Select type of backup based on the cron folder script has been called from
if [ "$DIR" == "/etc/cron.monthly" ]; then
        PERIOD="monthly"
elif [ "$DIR" == "/etc/cron.weekly" ]; then
        PERIOD="weekly"
else
        # Always fall back on daily, so we don't splatter
        # files all over the remote server by accident
        PERIOD="daily"
fi

### Create temporary folder
[ ! -d $DBBACKUP ] && mkdir -p $DBBACKUP || :

### Mark the backup so we know which is more recent for a restore
### This is inside the DB backup folder so we don't keep rsyncing
### new dummy files
touch $DBBACKUP/$NOW

### Backup phpBB3 database
$NICE $MYSQLHOTCOPY -u $DBUSER -p $DBPASS phpbb3 $DBBACKUP

### Backup Mediawiki database
$NICE $MYSQLDUMP -u $DBUSER -h $DBHOST -p$DBPASS wikidb > $DBBACKUP/wikidb.sql

### Backup to remote
$NICE $RSYNC --delete -vazr $DIRS $DBBACKUP $REMOTE/$PERIOD

### Remove temporary folders
rm -rf $BACKUP