#!/bin/zsh -f

# user definable parameters
# days: for how many days should backups be kept
days=30
backupdir=/backup/mysql
store=${backupdir}/store
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

  backupfile=${backupdir}/${hostname}__${dbname}__`date +%Y-%m-%d`.sql.bz2
  if [[ -f ${backupfile} ]]; then
    rm -f ${backupfile} 2>> ${logfile} || {echo "Backup file already exists and could not be deleted. Backup of target failed." >> ${logfile}; return}
  fi

  mysqldump --create-options --default-character-set="${charset}" --host="${hostname}" --hex-blob --lock-tables --password="${password}" --quote-names --user="${username}" "${dbname}" 2>> ${logfile} | bzip2 -c > ${backupfile}
  [[ ! -f ${backupfile} ]] && {echo "Failed to create backup."; return}
  if [[ "`date +%d`" == "01" && -d ${store} && -f ${backupfile} ]]; then
    echo "Today is the first day of the month. Making a copy of the backup in ${store} ..." >> ${logfile}
    cp ${backupfile} ${store} >> ${logfile} 2>&1
  fi
}


touch ${logfile} 2> /dev/null
[[ ! -w ${logfile} ]] && {echo "Error (${0:t}): cannot write to logfile (${logfile})!"; exit 1}

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

[[ ! -d ${backupdir} || ! -r ${backupdir} || ! -x ${backupdir} || ! -w ${backupdir} ]] && {echo "Backup directory (${backupdir}) does not exist or is not readable+writeable+searchable by current process. Backup failed." >> ${logfile}; exit 1}


# 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}


