summaryrefslogtreecommitdiff
path: root/hanoi-backup
blob: 421af57401fa8463536552ce4e8fa02891783fcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/bin/bash
####################################
#
# Tower of Hanoi Backup script.
# hanoi_backup v2.3.1 jeremdow@gmail.com
#
# This script will archive MySQL databases and specified files on the local host.
# If run as a daily cron job, archives are rotated on a Tower of Hanoi schedule.
# Archives from 1, 2, 4, 8, 16... $max days ago are retained depending on the setting.
#
####################################

# Configuration Settings

# MySQL login.
user="user"
password="password"

# Where to backup to.
dest="path"

# Backup files
files="/etc/mysql/my.cnf /etc/lighttpd /var/www"

# Oldest backup to keep (as a power of 2 in days)
max="32"

####################################

# Create archive filename.
date=$(date +%F)
hostname=$(hostname -s)
mysql_archive="$hostname-$date.sql.xz"
file_archive="$hostname-$date.tar.xz"

# Print start status message.
echo $(date)
echo "Backing up MySQL data to $dest/$mysql_archive"
echo

# Repair the database and create the backup
echo "Checking tables"
mysqlcheck -Ao -u$user -p$password
echo
echo "Dumping backup"
mysqldump --all-databases -v -u$user -p$password | xz > $dest/$mysql_archive
echo

# Print end status message.
echo "Backup $dest/$mysql_archive complete"
date
echo

# Print start status message.
echo $(date)
echo "Backing up locations: $files to $dest/$file_archive"
echo

# Backup files
tar -cvJf $dest/$file_archive $files

# Print end status message.
echo "Backup $dest/$file_archive complete"
date
echo

# Calculate the previous move in the cycle
((day=$(date +%s)/86400))
for (( i=1; i<=$max/2; i=2*i ))
    do
    (( rotation=$day & i ))
    if [ "$rotation" -eq "0" ]
    then
        (( expired=$i*2 ))
        break
    else
        expired="4"
    fi
done

# Remove the expired backups
expired_mysql=$hostname-$(date -d "$expired days ago" +%F).sql.xz
echo "Attempting to remove expired backup: $expired_mysql"
if [ -f $dest/$expired_mysql ]
then
    rm "$dest/$expired_mysql"
fi
expired_file=$hostname-$(date -d "$expired days ago" +%F).tar.xz
echo "Attempting to remove expired backup: $expired_file"
if [ -f $dest/$expired_file ]
then
    rm "$dest/$expired_file"
fi

# Finished
echo Complete!