Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
4096 rajveer 1
#!/bin/bash
2
#
3
# MySQL Backup Script
4
# VER. 2.5.1 - http://sourceforge.net/projects/automysqlbackup/
5
# Copyright (c) 2002-2003 wipe_out@lycos.co.uk
6
#
7
# This program is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License as published by
9
# the Free Software Foundation; either version 2 of the License, or
10
# (at your option) any later version.
11
#
12
# This program is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
# GNU General Public License for more details.
16
# 
17
# You should have received a copy of the GNU General Public License
18
# along with this program; if not, write to the Free Software
19
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
#
21
#=====================================================================
22
#=====================================================================
23
# Set the following variables to your system needs
24
# (Detailed instructions below variables)
25
#=====================================================================
26
#set -x
27
CONFIGFILE="/etc/automysqlbackup/automysqlbackup.conf"
28
 
29
if [ -r ${CONFIGFILE} ]; then
30
	# Read the configfile if it's existing and readable
31
	source ${CONFIGFILE}
32
else
33
	# do inline-config otherwise
34
	# To create a configfile just copy the code between "### START CFG ###" and "### END CFG ###"
35
	# to /etc/automysqlbackup/automysqlbackup.conf. After that you're able to upgrade this script
36
	# (copy a new version to its location) without the need for editing it.
37
	### START CFG ###
38
	# Username to access the MySQL server e.g. dbuser
39
	USERNAME=root
40
 
41
	# Password to access the MySQL server e.g. password
42
	PASSWORD=shop2020
43
 
44
	# Host name (or IP address) of MySQL server e.g localhost
45
	DBHOST=localhost
46
 
47
	# List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3"
48
	DBNAMES="all"
49
 
50
	# Backup directory location e.g /backups
51
	BACKUPDIR="/root/.backup"
52
 
53
	# Mail setup
54
	# What would you like to be mailed to you?
55
	# - log   : send only log file
56
	# - files : send log file and sql files as attachments (see docs)
57
	# - stdout : will simply output the log to the screen if run manually.
58
	# - quiet : Only send logs if an error occurs to the MAILADDR.
59
	MAILCONTENT="stdout"
60
 
61
	# Set the maximum allowed email size in k. (4000 = approx 5MB email [see docs])
62
	MAXATTSIZE="4000"
63
 
64
	# Email Address to send mail to? (user@domain.com)
65
	MAILADDR="root@localhost"
66
 
67
 
68
	# ============================================================
69
	# === ADVANCED OPTIONS ( Read the doc's below for details )===
70
	#=============================================================
71
 
72
	# List of DBBNAMES for Monthly Backups.
73
	MDBNAMES="${DBNAMES}"
74
 
75
	# List of DBNAMES to EXLUCDE if DBNAMES are set to all (must be in " quotes)
76
	DBEXCLUDE="information_schema"
77
 
78
	# Include CREATE DATABASE in backup?
79
	CREATE_DATABASE=no
80
 
81
	# Separate backup directory and file for each DB? (yes or no)
82
	SEPDIR=no
83
 
84
	# Which day do you want weekly backups? (1 to 7 where 1 is Monday)
85
	DOWEEKLY=6
86
 
87
	# Choose Compression type. (gzip or bzip2)
88
	COMP=gzip
89
 
90
	# Compress communications between backup server and MySQL server?
91
	COMMCOMP=no
92
 
93
	# Additionally keep a copy of the most recent backup in a seperate directory.
94
	LATEST=no
95
 
96
	#  The maximum size of the buffer for client/server communication. e.g. 16MB (maximum is 1GB)
97
	MAX_ALLOWED_PACKET=
98
 
99
	#  For connections to localhost. Sometimes the Unix socket file must be specified.
100
	SOCKET=
101
 
102
	# Command to run before backups (uncomment to use)
103
	#PREBACKUP="/etc/mysql-backup-pre"
104
 
105
	# Command run after backups (uncomment to use)
106
	#POSTBACKUP="/etc/mysql-backup-post"
107
	### END CFG ###
108
fi
109
 
110
#=====================================================================
111
# Options documantation
112
#=====================================================================
113
# Set USERNAME and PASSWORD of a user that has the appropriate permissions
114
# to backup ALL databases. (See mysql documentation for details)
115
# NEW in 2.5.1:
116
# - If USERNAME is set to "debian" and PASSWORD is unset or "" obtain
117
#   them from the file /etc/mysql/debian.cnf
118
# - First command line option "-c" for configfile
119
# - Interpretable Exit-States:
120
#    1: given configfile is not readable or does not exist
121
#    2: unknown option
122
#
123
# Set the DBHOST option to the server you wish to backup, leave the
124
# default to backup "this server".(to backup multiple servers make
125
# copies of this file and set the options for that server)
126
#
127
# Put in the list of DBNAMES(Databases)to be backed up. If you would like
128
# to backup ALL DBs on the server set DBNAMES="all".(if set to "all" then
129
# any new DBs will automatically be backed up without needing to modify
130
# this backup script when a new DB is created).
131
#
132
# If the DB you want to backup has a space in the name replace the space
133
# with a % e.g. "data base" will become "data%base"
134
# NOTE: Spaces in DB names may not work correctly when SEPDIR=no.
135
#
136
# You can change the backup storage location from /backups to anything
137
# you like by using the BACKUPDIR setting..
138
#
139
# The MAILCONTENT and MAILADDR options and pretty self explanitory, use
140
# these to have the backup log mailed to you at any email address or multiple
141
# email addresses in a space seperated list.
142
# (If you set mail content to "log" you will require access to the "mail" program
143
# on your server. If you set this to "files" you will have to have mutt installed
144
# on your server. If you set it to "stdout" it will log to the screen if run from 
145
# the console or to the cron job owner if run through cron. If you set it to "quiet"
146
# logs will only be mailed if there are errors reported. )
147
#
148
# MAXATTSIZE sets the largest allowed email attachments total (all backup files) you
149
# want the script to send. This is the size before it is encoded to be sent as an email
150
# so if your mail server will allow a maximum mail size of 5MB I would suggest setting
151
# MAXATTSIZE to be 25% smaller than that so a setting of 4000 would probably be fine.
152
#
153
# Finally copy automysqlbackup.sh to anywhere on your server and make sure
154
# to set executable permission. You can also copy the script to
155
# /etc/cron.daily to have it execute automatically every night or simply
156
# place a symlink in /etc/cron.daily to the file if you wish to keep it 
157
# somwhere else.
158
# NOTE:On Debian copy the file with no extention for it to be run
159
# by cron e.g just name the file "automysqlbackup"
160
#
161
# Thats it..
162
#
163
#
164
# === Advanced options doc's ===
165
#
166
# The list of MDBNAMES is the DB's to be backed up only monthly. You should
167
# always include "mysql" in this list to backup your user/password
168
# information along with any other DBs that you only feel need to
169
# be backed up monthly. (if using a hosted server then you should
170
# probably remove "mysql" as your provider will be backing this up)
171
# NOTE: If DBNAMES="all" then MDBNAMES has no effect as all DBs will be backed
172
# up anyway.
173
#
174
# If you set DBNAMES="all" you can configure the option DBEXCLUDE. Other
175
# wise this option will not be used.
176
# This option can be used if you want to backup all dbs, but you want 
177
# exclude some of them. (eg. a db is to big).
178
#
179
# Set CREATE_DATABASE to "yes" (the default) if you want your SQL-Dump to create
180
# a database with the same name as the original database when restoring.
181
# Saying "no" here will allow your to specify the database name you want to
182
# restore your dump into, making a copy of the database by using the dump
183
# created with automysqlbackup.
184
# NOTE: Not used if SEPDIR=no
185
#
186
# The SEPDIR option allows you to choose to have all DBs backed up to
187
# a single file (fast restore of entire server in case of crash) or to
188
# seperate directories for each DB (each DB can be restored seperately
189
# in case of single DB corruption or loss).
190
#
191
# To set the day of the week that you would like the weekly backup to happen
192
# set the DOWEEKLY setting, this can be a value from 1 to 7 where 1 is Monday,
193
# The default is 6 which means that weekly backups are done on a Saturday.
194
#
195
# COMP is used to choose the copmression used, options are gzip or bzip2.
196
# bzip2 will produce slightly smaller files but is more processor intensive so
197
# may take longer to complete.
198
#
199
# COMMCOMP is used to enable or diable mysql client to server compression, so
200
# it is useful to save bandwidth when backing up a remote MySQL server over
201
# the network. 
202
#
203
# LATEST is to store an additional copy of the latest backup to a standard
204
# location so it can be downloaded bt thrid party scripts.
205
#
206
# If the DB's being backed up make use of large BLOB fields then you may need
207
# to increase the MAX_ALLOWED_PACKET setting, for example 16MB..
208
#
209
# When connecting to localhost as the DB server (DBHOST=localhost) sometimes
210
# the system can have issues locating the socket file.. This can now be set
211
# using the SOCKET parameter.. An example may be SOCKET=/private/tmp/mysql.sock
212
#
213
# Use PREBACKUP and POSTBACKUP to specify Per and Post backup commands
214
# or scripts to perform tasks either before or after the backup process.
215
#
216
#
217
#=====================================================================
218
# Backup Rotation..
219
#=====================================================================
220
#
221
# Daily Backups are rotated weekly..
222
# Weekly Backups are run by default on Saturday Morning when
223
# cron.daily scripts are run...Can be changed with DOWEEKLY setting..
224
# Weekly Backups are rotated on a 5 week cycle..
225
# Monthly Backups are run on the 1st of the month..
226
# Monthly Backups are rotated on a 5 month cycle...
227
# It may be a good idea to copy Monthly backups offline or to another
228
# server..
229
#
230
#=====================================================================
231
# Please Note!!
232
#=====================================================================
233
#
234
# I take no resposibility for any data loss or corruption when using
235
# this script..
236
# This script will not help in the event of a hard drive crash. If a 
237
# copy of the backup has not be stored offline or on another PC..
238
# You should copy your backups offline regularly for best protection.
239
#
240
# Happy backing up...
241
#
242
#=====================================================================
243
# Restoring
244
#=====================================================================
245
# Firstly you will need to uncompress the backup file.
246
# eg.
247
# gunzip file.gz (or bunzip2 file.bz2)
248
#
249
# Next you will need to use the mysql client to restore the DB from the
250
# sql file.
251
# eg.
252
# mysql --user=username --pass=password --host=dbserver database < /path/file.sql
253
# or
254
# mysql --user=username --pass=password --host=dbserver -e "source /path/file.sql" database
255
#
256
# NOTE: Make sure you use "<" and not ">" in the above command because
257
# you are piping the file.sql to mysql and not the other way around.
258
#
259
# Lets hope you never have to use this.. :)
260
#
261
#=====================================================================
262
# Change Log
263
#=====================================================================
264
#
265
# VER 2.5.1-01 - (2010-07-06)
266
#     - Fixed pathname bug item #3025849 (by Johannes Kolter)
267
# VER 2.5.1 - (2010-07-04)
268
#     - Added support for default and optional config file (by Johannes Kolter)
269
#     - Rotating after backup was successful whith find(1) (by Johannes Kolter)
270
#     - Implementation of Variables containing full path to binaries to
271
#       avoid possibly confusion with aliases or builtins. (by Johannes Kolter)
272
#     - Fixed bug where weekly backups were not being rotated.
273
#       Added rotation of 5 monthly backups
274
#       Now all old backups are deleted, not only the most recent one
275
#       (inspired by oleg@bintime.com)
276
#     - Use Debian special-file to access database (by Johannes Kolter)
277
#     - Fixed bug ID: 1438565
278
#       Moved IO redirection to a place before decicions are made and actions are taken.
279
#       (inspired by Derk Bernhardt)
280
#     - Fixed bug ID: #3000316 (reported by Sascha Feldhorst)
281
#     - Fixed bug ID: #1529458 (reported by Natalie ( njwood ))
282
#     - Fixed bug ID: #1548919 (reported by Piotr Kuczynski)
283
# VER 2.5 - (2006-01-15)
284
#		Added support for setting MAXIMUM_PACKET_SIZE and SOCKET parameters (suggested by Yvo van Doorn)
285
# VER 2.4 - (2006-01-23)
286
#    Fixed bug where weekly backups were not being rotated. (Fix by wolf02)
287
#    Added hour an min to backup filename for the case where backups are taken multiple
288
#    times in a day. NOTE This is not complete support for mutiple executions of the script
289
#    in a single day.
290
#    Added MAILCONTENT="quiet" option, see docs for details. (requested by snowsam)
291
#    Updated path statment for compatibility with OSX.
292
#    Added "LATEST" to additionally store the last backup to a standard location. (request by Grant29)
293
# VER 2.3 - (2005-11-07)
294
#    Better error handling and notification of errors (a long time coming)
295
#    Compression on Backup server to MySQL server communications. 
296
# VER 2.2 - (2004-12-05)
297
#    Changed from using depricated "-N" to "--skip-column-names".
298
#    Added ability to have compressed backup's emailed out. (code from Thomas Heiserowski)
299
#    Added maximum attachment size setting.
300
# VER 2.1 - (2004-11-04)
301
#    Fixed a bug in daily rotation when not using gzip compression. (Fix by Rob Rosenfeld)
302
# VER 2.0 - (2004-07-28)
303
#    Switched to using IO redirection instead of pipeing the output to the logfile.
304
#    Added choice of compression of backups being gzip of bzip2.
305
#    Switched to using functions to facilitate more functionality.
306
#    Added option of either gzip or bzip2 compression. 
307
# VER 1.10 - (2004-07-17)
308
#    Another fix for spaces in the paths (fix by Thomas von Eyben)
309
#    Fixed bug when using PREBACKUP and POSTBACKUP commands containing many arguments.
310
# VER 1.9 - (2004-05-25)
311
#    Small bug fix to handle spaces in LOGFILE path which contains spaces (reported by Thomas von Eyben)
312
#    Updated docs to mention that Log email can be sent to multiple email addresses.
313
# VER 1.8 - (2004-05-01)
314
#    Added option to make backups restorable to alternate database names
315
#    meaning that a copy of the database can be created (Based on patch by Rene Hoffmann)
316
#    Seperated options into standard and advanced.
317
#    Removed " from single file dump DBMANES because it caused an error but
318
#    this means that if DB's have spaces in the name they will not dump when SEPDIR=no.
319
#    Added -p option to mkdir commands to create multiple subdirs without error.
320
#    Added disk usage and location to the bottom of the backup report.
321
# VER 1.7 - (2004-04-22)
322
#    Fixed an issue where weelky backups would only work correctly if server
323
#    locale was set to English (issue reported by Tom Ingberg)
324
#    used "eval" for "rm" commands to try and resolve rotation issues.
325
#    Changed name of status log so multiple scripts can be run at the same time.
326
# VER 1.6 - (2004-03-14)
327
#   Added PREBACKUP and POSTBACKUP command functions. (patch by markpustjens)
328
#   Added support for backing up DB's with Spaces in the name.
329
#   (patch by markpustjens)
330
# VER 1.5 - (2004-02-24)
331
#   Added the ability to exclude DB's when the "all" option is used.
332
#   (Patch by kampftitan)
333
# VER 1.4 - (2004-02-02)
334
#   Project moved to Sourceforge.net
335
# VER 1.3 - (2003-09-25)
336
#   Added support for backing up "all" databases on the server without
337
#    having to list each one seperately in the configuration.
338
#   Added DB restore instructions.
339
# VER 1.2 - (2003-03-16)
340
#   Added server name to the backup log so logs from multiple servers
341
#   can be easily identified.
342
# VER 1.1 - (2003-03-13)
343
#   Small Bug fix in monthly report. (Thanks Stoyanski)
344
#   Added option to email log to any email address. (Inspired by Stoyanski)
345
#   Changed Standard file name to .sh extention.
346
#   Option are set using yes and no rather than 1 or 0.
347
# VER 1.0 - (2003-01-30)
348
#   Added the ability to have all databases backup to a single dump
349
#   file or seperate directory and file for each database.
350
#   Output is better for log keeping.
351
# VER 0.6 - (2003-01-22)
352
#   Bug fix for daily directory (Added in VER 0.5) rotation.
353
# VER 0.5 - (2003-01-20)
354
#   Added "daily" directory for daily backups for neatness (suggestion by Jason)
355
#   Added DBHOST option to allow backing up a remote server (Suggestion by Jason)
356
#   Added "--quote-names" option to mysqldump command.
357
#   Bug fix for handling the last and first of the year week rotation.
358
# VER 0.4 - (2002-11-06)
359
#   Added the abaility for the script to create its own directory structure.
360
# VER 0.3 - (2002-10-01)
361
#   Changed Naming of Weekly backups so they will show in order.
362
# VER 0.2 - (2002-09-27)
363
#   Corrected weekly rotation logic to handle weeks 0 - 10 
364
# VER 0.1 - (2002-09-21)
365
#   Initial Release
366
#
367
#=====================================================================
368
#=====================================================================
369
#=====================================================================
370
#
371
# Should not need to be modified from here down!!
372
#
373
#=====================================================================
374
#=====================================================================
375
#=====================================================================
376
#
377
# Full pathname to binaries to avoid problems with aliases and builtins etc.
378
#
379
WHICH="`which which`"
380
AWK="`${WHICH} gawk`"
381
LOGGER="`${WHICH} logger`"
382
ECHO="`${WHICH} echo`"
383
CAT="`${WHICH} cat`"
384
BASENAME="`${WHICH} basename`"
385
DATEC="`${WHICH} date`"
386
DU="`${WHICH} du`"
387
EXPR="`${WHICH} expr`"
388
FIND="`${WHICH} find`"
389
RM="`${WHICH} rm`"
390
MYSQL="`${WHICH} mysql`"
391
MYSQLDUMP="`${WHICH} mysqldump`"
392
GZIP="`${WHICH} gzip`"
393
BZIP2="`${WHICH} bzip2`"
394
CP="`${WHICH} cp`"
395
HOSTNAMEC="`${WHICH} hostname`"
396
SED="`${WHICH} sed`"
397
GREP="`${WHICH} grep`"
398
 
399
function get_debian_pw() {
400
	if [ -r /etc/mysql/debian.cnf ]; then
401
		eval $(${AWK} '
402
			! user && /^[[:space:]]*user[[:space:]]*=[[:space:]]*/ {
403
				print "USERNAME=" gensub(/.+[[:space:]]+([^[:space:]]+)[[:space:]]*$/, "\\1", "1"); user++
404
			}
405
			! pass && /^[[:space:]]*password[[:space:]]*=[[:space:]]*/ {
406
				print "PASSWORD=" gensub(/.+[[:space:]]+([^[:space:]]+)[[:space:]]*$/, "\\1", "1"); pass++
407
			}' /etc/mysql/debian.cnf
408
		)
409
	else
410
		${LOGGER} "${PROGNAME}: File \"/etc/mysql/debian.cnf\" not found."
411
		exit 1
412
	fi
413
}
414
 
415
[ "x${USERNAME}" = "xdebian" -a "x${PASSWORD}" = "x" ] && get_debian_pw 
416
 
417
while [ $# -gt 0 ]; do
418
	case $1 in
419
		-c)
420
			if [ -r "$2" ]; then
421
				source "$2"
422
				shift 2
423
			else
424
				${ECHO} "Ureadable config file \"$2\""
425
				exit 1
426
			fi
427
			;;
428
		*)
429
			${ECHO} "Unknown Option \"$1\""
430
			exit 2
431
			;;
432
	esac
433
done
434
 
435
export LC_ALL=C
436
PROGNAME=`${BASENAME} $0`
437
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/mysql/bin 
438
DATE=`${DATEC} +%Y-%m-%d_%Hh%Mm`				# Datestamp e.g 2002-09-21
439
DOW=`${DATEC} +%A`							# Day of the week e.g. Monday
440
DNOW=`${DATEC} +%u`						# Day number of the week 1 to 7 where 1 represents Monday
441
DOM=`${DATEC} +%d`							# Date of the Month e.g. 27
442
M=`${DATEC} +%B`							# Month e.g January
443
W=`${DATEC} +%V`							# Week Number e.g 37
444
VER=2.5.1									# Version Number
445
LOGFILE=${BACKUPDIR}/${DBHOST}-`${DATEC} +%N`.log		# Logfile Name
446
LOGERR=${BACKUPDIR}/ERRORS_${DBHOST}-`${DATEC} +%N`.log		# Logfile Name
447
BACKUPFILES=""
448
OPT="--single-transaction --flush-logs --master-data=2"			# OPT string for use with mysqldump ( see man mysqldump )
449
 
450
# IO redirection for logging.
451
touch ${LOGFILE}
452
exec 6>&1           # Link file descriptor #6 with stdout.
453
                    # Saves stdout.
454
exec > ${LOGFILE}     # stdout replaced with file ${LOGFILE}.
455
touch ${LOGERR}
456
exec 7>&2           # Link file descriptor #7 with stderr.
457
                    # Saves stderr.
458
exec 2> ${LOGERR}     # stderr replaced with file ${LOGERR}.
459
 
460
# Add --compress mysqldump option to ${OPT}
461
if [ "${COMMCOMP}" = "yes" ];
462
	then
463
		OPT="${OPT} --compress"
464
	fi
465
 
466
# Add --max_allowed_packet=... mysqldump option to ${OPT}
467
if [ "${MAX_ALLOWED_PACKET}" ];
468
	then
469
		OPT="${OPT} --max_allowed_packet=${MAX_ALLOWED_PACKET}"
470
	fi
471
 
472
# Create required directories
473
if [ ! -e "${BACKUPDIR}" ]		# Check Backup Directory exists.
474
	then
475
	mkdir -p "${BACKUPDIR}"
476
fi
477
 
478
if [ ! -e "${BACKUPDIR}/daily" ]		# Check Daily Directory exists.
479
	then
480
	mkdir -p "${BACKUPDIR}/daily"
481
fi
482
 
483
if [ ! -e "${BACKUPDIR}/weekly" ]		# Check Weekly Directory exists.
484
	then
485
	mkdir -p "${BACKUPDIR}/weekly"
486
fi
487
 
488
if [ ! -e "${BACKUPDIR}/monthly" ]	# Check Monthly Directory exists.
489
	then
490
	mkdir -p "${BACKUPDIR}/monthly"
491
fi
492
 
493
if [ "${LATEST}" = "yes" ]
494
then
495
	if [ ! -e "${BACKUPDIR}/latest" ]	# Check Latest Directory exists.
496
	then
497
		mkdir -p "${BACKUPDIR}/latest"
498
	fi
499
eval ${RM} -fv "${BACKUPDIR}/latest/*"
500
fi
501
 
502
 
503
# Functions
504
 
505
# Database dump function
506
dbdump () {
507
echo ${MYSQLDUMP} --user=${USERNAME} --password=${PASSWORD} --host=${DBHOST} ${OPT} ${1}
508
${MYSQLDUMP} --user=${USERNAME} --password=${PASSWORD} --host=${DBHOST} ${OPT} ${1} > ${2}
509
return $?
510
}
511
 
512
# Compression function plus latest copy
513
SUFFIX=""
514
compression () {
515
if [ "${COMP}" = "gzip" ]; then
516
	${GZIP} -f "${1}"
517
	${ECHO}
518
	${ECHO} Backing up "${1}" using gzip
519
	${GZIP} -l "${1}.gz"
520
	SUFFIX=".gz"
521
elif [ "${COMP}" = "bzip2" ]; then
522
	${ECHO} Backing up "${1}" using bzip2
523
	${BZIP2} -f -v ${1} 2>&1
524
	SUFFIX=".bz2"
525
else
526
	${ECHO} "No compression option set, check advanced settings"
527
fi
528
if [ "${LATEST}" = "yes" ]; then
529
	${CP} ${1}${SUFFIX} "${BACKUPDIR}/latest/"
530
fi	
531
return 0
532
}
533
 
534
 
535
# Run command before we begin
536
if [ "${PREBACKUP}" ]
537
	then
538
	${ECHO} ======================================================================
539
	${ECHO} "Prebackup command output."
540
	${ECHO}
541
	eval ${PREBACKUP}
542
	${ECHO}
543
	${ECHO} ======================================================================
544
	${ECHO}
545
fi
546
 
547
 
548
if [ "${SEPDIR}" = "yes" ]; then # Check if CREATE DATABSE should be included in Dump
549
	if [ "${CREATE_DATABASE}" = "no" ]; then
550
		OPT="${OPT} --no-create-db"
551
	else
552
		OPT="${OPT} --databases"
553
	fi
554
fi
555
 
556
# Hostname for LOG information
557
if [ "${DBHOST}" = "localhost" ]; then
558
	HOST=`${HOSTNAMEC}`
559
	if [ "${SOCKET}" ]; then
560
		OPT="${OPT} --socket=${SOCKET}"
561
	fi
562
else
563
	HOST=${DBHOST}
564
fi
565
 
566
 
567
${ECHO} ======================================================================
568
${ECHO} AutoMySQLBackup VER ${VER}
569
${ECHO} http://sourceforge.net/projects/automysqlbackup/
570
${ECHO} 
571
${ECHO} Backup of Database Server - ${HOST}
572
${ECHO} ======================================================================
573
 
574
# Test is seperate DB backups are required
575
if [ "${SEPDIR}" = "yes" ]; then
576
# If backing up all DBs on the server
577
if [ "${DBNAMES}" = "all" ]; then
578
        DBNAMES="`${MYSQL} --user=${USERNAME} --password=${PASSWORD} --host=${DBHOST} --batch --skip-column-names -e "show databases"| ${SED} 's/ /%/g'`"
579
 
580
	# If DBs are excluded
581
	for exclude in ${DBEXCLUDE}
582
	do
583
		DBNAMES=`${ECHO} ${DBNAMES} | ${SED} "s/\b${exclude}\b//g"`
584
	done
585
 
586
        MDBNAMES=${DBNAMES}
587
fi
588
${ECHO} Backup Start Time `${DATEC}`
589
${ECHO} ======================================================================
590
	# Monthly Full Backup of all Databases
591
	if [ ${DOM} = "01" ]; then
592
		for MDB in ${MDBNAMES}
593
		do
594
 
595
			 # Prepare ${DB} for using
596
		        MDB="`${ECHO} ${MDB} | ${SED} 's/%/ /g'`"
597
 
598
			if [ ! -e "${BACKUPDIR}/monthly/${MDB}" ]		# Check Monthly DB Directory exists.
599
			then
600
				mkdir -p "${BACKUPDIR}/monthly/${MDB}"
601
			fi
602
			${ECHO} Monthly Backup of ${MDB}...
603
				dbdump "${MDB}" "${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.sql"
604
				[ $? -eq 0 ] && {
605
					${ECHO} "Rotating 5 month backups for ${MDB}"
606
					${FIND} "${BACKUPDIR}/monthly/${MDB}" -mtime +150 -type f -exec ${RM} -v {} \; 
607
				}
608
				compression "${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.sql"
609
				BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.sql${SUFFIX}"
610
			${ECHO} ----------------------------------------------------------------------
611
		done
612
	fi
613
 
614
	for DB in ${DBNAMES}
615
	do
616
	# Prepare ${DB} for using
617
	DB="`${ECHO} ${DB} | ${SED} 's/%/ /g'`"
618
 
619
	# Create Seperate directory for each DB
620
	if [ ! -e "${BACKUPDIR}/daily/${DB}" ]		# Check Daily DB Directory exists.
621
		then
622
		mkdir -p "${BACKUPDIR}/daily/${DB}"
623
	fi
624
 
625
	if [ ! -e "${BACKUPDIR}/weekly/${DB}" ]		# Check Weekly DB Directory exists.
626
		then
627
		mkdir -p "${BACKUPDIR}/weekly/${DB}"
628
	fi
629
 
630
	# Weekly Backup
631
	if [ ${DNOW} = ${DOWEEKLY} ]; then
632
		${ECHO} Weekly Backup of Database \( ${DB} \)
633
		${ECHO}
634
			dbdump "${DB}" "${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.sql"
635
			[ $? -eq 0 ] && {
636
				${ECHO} Rotating 5 weeks Backups...
637
				${FIND} "${BACKUPDIR}/weekly/${DB}" -mtime +35 -type f -exec ${RM} -v {} \; 
638
			}
639
			compression "${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.sql"
640
			BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.sql${SUFFIX}"
641
		${ECHO} ----------------------------------------------------------------------
642
 
643
	# Daily Backup
644
	else
645
		${ECHO} Daily Backup of Database \( ${DB} \)
646
		${ECHO}
647
			dbdump "${DB}" "${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.sql"
648
			[ $? -eq 0 ] && {
649
				${ECHO} Rotating last weeks Backup...
650
				${FIND} "${BACKUPDIR}/daily/${DB}" -mtime +6 -type f -exec ${RM} -v {} \; 
651
			}
652
			compression "${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.sql"
653
			BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.sql${SUFFIX}"
654
		${ECHO} ----------------------------------------------------------------------
655
	fi
656
	done
657
${ECHO} Backup End `${DATEC}`
658
${ECHO} ======================================================================
659
 
660
 
661
else # One backup file for all DBs
662
# If backing up all DBs on the server
663
if [ "${DBNAMES}" = "all" ]; then
664
        MDBNAMES="--all-databases"
665
fi
666
${ECHO} Backup Start `${DATEC}`
667
${ECHO} ======================================================================
668
	# Monthly Full Backup of all Databases
669
	if [ ${DOM} = "01" ]; then
670
		${ECHO} Monthly full Backup of \( ${MDBNAMES} \)...
671
			dbdump "${MDBNAMES}" "${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.sql"
672
			[ $? -eq 0 ] && {
673
				${ECHO} "Rotating 5 month backups."
674
				${FIND} "${BACKUPDIR}/monthly" -mtime +150 -type f -exec ${RM} -v {} \; 
675
			}
676
			compression "${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.sql"
677
			BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.sql${SUFFIX}"
678
		${ECHO} ----------------------------------------------------------------------
679
	fi
680
 
681
	# Weekly Backup
682
	if [ ${DNOW} = ${DOWEEKLY} ]; then
683
		${ECHO} Weekly Backup of Databases \( ${DBNAMES} \)
684
		${ECHO}
685
		${ECHO}
686
			dbdump "${MDBNAMES}" "${BACKUPDIR}/weekly/week.${W}.${DATE}.sql"
687
			[ $? -eq 0 ] && {
688
				${ECHO} Rotating 5 weeks Backups...
689
				${FIND} "${BACKUPDIR}/weekly/" -mtime +35 -type f -exec ${RM} -v {} \; 
690
			}
691
			compression "${BACKUPDIR}/weekly/week.${W}.${DATE}.sql"
692
			BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/weekly/week.${W}.${DATE}.sql${SUFFIX}"
693
		${ECHO} ----------------------------------------------------------------------
694
 
695
	# Daily Backup
696
	else
697
		${ECHO} Daily Backup of Databases \( ${DBNAMES} \)
698
		${ECHO}
699
		${ECHO}
700
			dbdump "${MDBNAMES}" "${BACKUPDIR}/daily/${DATE}.${DOW}.sql"
701
			[ $? -eq 0 ] && {
702
				${ECHO} Rotating last weeks Backup...
703
				${FIND} "${BACKUPDIR}/daily" -mtime +6 -type f -exec ${RM} -v {} \; 
704
			}
705
			compression "${BACKUPDIR}/daily/${DATE}.${DOW}.sql"
706
			BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/daily/${DATE}.${DOW}.sql${SUFFIX}"
707
		${ECHO} ----------------------------------------------------------------------
708
	fi
709
${ECHO} Backup End Time `${DATEC}`
710
${ECHO} ======================================================================
711
fi
712
${ECHO} Total disk space used for backup storage..
713
${ECHO} Size - Location
714
${ECHO} `${DU} -hs "${BACKUPDIR}"`
715
${ECHO}
716
${ECHO} ======================================================================
717
${ECHO} If you find AutoMySQLBackup valuable please make a donation at
718
${ECHO} http://sourceforge.net/project/project_donations.php?group_id=101066
719
${ECHO} ======================================================================
720
 
721
# Run command when we're done
722
if [ "${POSTBACKUP}" ]
723
	then
724
	${ECHO} ======================================================================
725
	${ECHO} "Postbackup command output."
726
	${ECHO}
727
	eval ${POSTBACKUP}
728
	${ECHO}
729
	${ECHO} ======================================================================
730
fi
731
 
732
#Clean up IO redirection
733
exec 1>&6 6>&-      # Restore stdout and close file descriptor #6.
734
exec 2>&7 7>&-      # Restore stdout and close file descriptor #7.
735
 
736
if [ "${MAILCONTENT}" = "files" ]
737
then
738
	if [ -s "${LOGERR}" ]
739
	then
740
		# Include error log if is larger than zero.
741
		BACKUPFILES="${BACKUPFILES} ${LOGERR}"
742
		ERRORNOTE="WARNING: Error Reported - "
743
	fi
744
	#Get backup size
745
	ATTSIZE=`${DU} -c ${BACKUPFILES} | ${GREP} "[[:digit:][:space:]]total$" |${SED} s/\s*total//`
746
	if [ ${MAXATTSIZE} -ge ${ATTSIZE} ]
747
	then
748
		BACKUPFILES=`${ECHO} "${BACKUPFILES}" | ${SED} -e "s# # -a #g"`	#enable multiple attachments
749
		mutt -s "${ERRORNOTE} MySQL Backup Log and SQL Files for ${HOST} - ${DATE}" ${BACKUPFILES} ${MAILADDR} < ${LOGFILE}		#send via mutt
750
	else
751
		${CAT} "${LOGFILE}" | mail -s "WARNING! - MySQL Backup exceeds set maximum attachment size on ${HOST} - ${DATE}" ${MAILADDR}
752
	fi
753
elif [ "${MAILCONTENT}" = "log" ]
754
then
755
	${CAT} "${LOGFILE}" | mail -s "MySQL Backup Log for ${HOST} - ${DATE}" ${MAILADDR}
756
	if [ -s "${LOGERR}" ]
757
		then
758
			${CAT} "${LOGERR}" | mail -s "ERRORS REPORTED: MySQL Backup error Log for ${HOST} - ${DATE}" ${MAILADDR}
759
	fi	
760
elif [ "${MAILCONTENT}" = "quiet" ]
761
then
762
	if [ -s "${LOGERR}" ]
763
		then
764
			${CAT} "${LOGERR}" | mail -s "ERRORS REPORTED: MySQL Backup error Log for ${HOST} - ${DATE}" ${MAILADDR}
765
			${CAT} "${LOGFILE}" | mail -s "MySQL Backup Log for ${HOST} - ${DATE}" ${MAILADDR}
766
	fi
767
else
768
	if [ -s "${LOGERR}" ]
769
		then
770
			${CAT} "${LOGFILE}"
771
			${ECHO}
772
			${ECHO} "###### WARNING ######"
773
			${ECHO} "Errors reported during AutoMySQLBackup execution.. Backup failed"
774
			${ECHO} "Error log below.."
775
			${CAT} "${LOGERR}"
776
	else
777
		${CAT} "${LOGFILE}"
778
	fi	
779
fi
780
 
781
if [ -s "${LOGERR}" ]
782
	then
783
		STATUS=1
784
	else
785
		STATUS=0
786
fi
787
 
788
# Clean up Logfile
789
eval ${RM} -f "${LOGFILE}"
790
eval ${RM} -f "${LOGERR}"
791
 
792
exit ${STATUS}