#!/bin/bash
#
# Script to hotcopy all MySQL databases.
# Author: Erik Johansson <erik@ejohansson.se>
# Last update: 2012-10-14

PATH=/bin:/sbin:/usr/sbin:/usr/bin

# What to output.
# 0: Only errors, 1: "Pretty" output, 2: Everything
OUTPUT_LEVEL=1

# MySQL settings
MYSQL_DIR='/var/lib/mysql'
MYSQL_BACKUP_DIR='/var/backups/mysql'

### END SETTINGS ###

# Backup all MySQL DBs (except test and performance_schema) to MYSQL_BACKUP_DIR
_DBS=$(find $MYSQL_DIR -mindepth 1 -maxdepth 1 -type d ! -name performance_schema ! -name test -printf '%f ')
_FAILED=0

for db in $_DBS; do
	if [ $OUTPUT_LEVEL -eq 1 ]; then echo -n "Hotcopying database $db... "; fi
	if [ $OUTPUT_LEVEL -le 1 ]; then QUIET='-q'; fi

	_OUTPUT=$(mysqlhotcopy --allowold $QUIET $db $MYSQL_BACKUP_DIR 2>&1)
	_EXIT=$?

	if [ $_EXIT -eq 0 ]; then
		if [ $OUTPUT_LEVEL -eq 1 ]; then 
			echo "done";
		elif [ $OUTPUT_LEVEL -eq 2 ]; then
			echo $_OUTPUT
		fi
	else
		_FAILED=$(expr $_FAILED + 1)
		if [ $OUTPUT_LEVEL -eq 1 ]; then
			tput setaf 1; echo "failed"
			tput setaf 3; echo -e "$_OUTPUT" 1>&2
		else
			tput setaf 1; echo $_OUTPUT 1>&2
		fi
		tput op
	fi
done

if [ $_FAILED -eq 0 ]; then
	if [ $OUTPUT_LEVEL -ge 1 ]; then echo -e "\nAll databases successfully copied."; fi
else
	tput setaf 1; echo -e "\nFailed to copy $_FAILED databases."; tput op
fi

exit $_FAILED
