#!/bin/zsh -f

# user definable parameters
# days: for how many days should backups be kept
days=30
backupdir=/backup/mysql
logfile=${backupdir}/backup.log


# parameters: username, password, hostname, dbname, characterset
function do_backup() {
  username=${1}
  password=${2}
  hostname=${3}
  dbname=${4}
  charset=${5}
  echo "
`date`
Parameters:
  username=${username}
  password=${(l:${#password}::*:)}
  hostname=${hostname}
  dbname=${dbname}
  characterset=${charset}" >> ${logfile}
  [[ ${#} -lt 5 ]] && {echo "Not enough parameters!" >> ${logfile} } && return
  mysqldump --create-options --default-character-set="${charset}" --host="${hostname}" --hex-blob --lock-tables --password="${password}" --quote-names --user="${username}" "${dbname}" 2>> ${logfile} | bzip2 -c > ${backupdir}/${hostname}__${dbname}__`date +%Y-%m-%d`.sql.bz2
}

echo "**********************************
Starting backup at: `date`" >> ${logfile}


# List of backups
# parameters: username password hostname dbname characterset
do_backup "backup_jack" "very_secret_password1" mysql1.example.com jack_db utf8
do_backup "backup_jane" "very_secret_password2" mysql2.example.com jane_db utf8


echo "
Cleaning up old backups ..." >> ${logfile}
[[ -d ${backupdir}  && ${days} -gt 0 ]] && find ${backupdir} -xdev -maxdepth 1 -type f -name '*.sql.bz2' -ctime ${days} -exec rm -f {} ";" -printf "%f was deleted.\n" >> ${logfile} 2>&1
echo "
End of backup at: `date`
" >> ${logfile}

