#!/bin/bash
# By: john stile
# Purpose: to backup mysql database
#
Log="/backup/backup-$(date +%Y-%m-%d-%s).log"
DEBUG=1
#---------------------------------------
# Function check_success:
#  Displays exit status of previous command,
#  And exit out if command failed.
check_success(){
if [ $? -ne 0 ]; then
  echo "[!!]  FAIL:  ${TASK}"
  if [ $DEBUG -ne 0 ]; then
    # For testing, exit to shell
    /bin/bash
  else
    # For production, quit program
    exit 1
  fi
else
  echo "[OK]  SUCCESS:  ${TASK}"
fi
}
{
echo "-------------------------------"
TASK="Set variables"
echo "[>>]  ${TASK}"
backup_area="/backup/mysql"
archive_dir="backup-"$(date +%Y-%m-%d-%s)
archive_tar="${archive_dir}.tar.gz"
mysql_user="root"
mysql_pass="pass"
mysql_databases="apan cacti mysql nagios perfparse vegadns"
echo "      DEBUG=${DEBUG}"
echo "      backup_area=${backup_area}"
echo "      archive_dir=${archive_dir}"
echo "      archive_tar=${archive_tar}"
check_success
echo "-------------------------------"
if [[ ! -d "${backup_area}" ]]; then
    mkdir -p "${backup_area}"
fi
echo "-------------------------------"
TASK="Delete old backups"
files=`find  "${backup_area}" -name "backup-*" -mtime +14`
for file in $files
do
  TASK="${TASK} - ${file}"
  echo "[>>]  ${TASK}"
  rm -rf "${file}"
  check_success
done
echo "-------------------------------"
TASK="Create temporary backup dir if it doesn't exist"
if [ ! -d "${backup_area}/${archive_dir}" ]; then
  echo "[>>]  ${TASK}"
  echo "[--]  creating backup dir: ${backup_area}/${archive_dir}"
  mkdir "${backup_area}/${archive_dir}"
  check_success
fi
echo "-------------------------------"
TASK="Run Backup"
for i in ${mysql_databases}; do
  TASK="Run Backup of: ${i}"
  echo "[>>]  ${TASK}"
  # Hot copy only works on MyIsam, not innoDB tables.
  # Switching to mysqldump
  #NEW#
  time /usr/bin/mysqldump --user="${mysql_user}" --password="${mysql_pass}" --database "${i}" > "${backup_area}/${archive_dir}/${i}.sql"
  check_success
done
echo "-------------------------------"
TASK="Tar it up"
echo "[>>]  ${TASK}"
cd "${backup_area}" \
&& /bin/tar -zcvf "${archive_tar}" "${archive_dir}"
check_success
echo "-------------------------------"
TASK="Remove backup directory"
echo "[>>]  ${TASK}"
rm -rf  "${backup_area}/${archive_dir}"
check_success
echo "-------------------------------"
echo "DONE"
} > "$Log" 2>&1

