#!/bin/bash
#
# This file is part of vbackup.
#
# vbackup is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# vbackup is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with vbackup  If not, see <http://www.gnu.org/licenses/>.
#
# $Id: mysql 3393 2012-03-06 21:00:03Z v13 $
#
# Description
#
#	Backup a mysql database
#

NAME="mysql"
VERSION="$PACKAGE_VERSION"
DESC="Backup mysql databases"
LICENSE="$PACKAGE_LICENSE"
COPYRIGHT="$PACKAGE_COPYRIGHT"
CONTACT="$PACKAGE_BUGREPORT"

# Display help
do_help()
{
	cat << _END
Configuration options:
	DATABASES	A space separated list of databases to backup.
			Set this to '-' to backup all databases. (required)
	MYUSER		The username to use to connect (required)
	PASSWORD	The password to use to connect (insecure)
	MYSQL		The path to mysql executable
	MYSQLDUMP	The path to mysqldump executable
	MYSQLDUMPEXTRA	Extra parameters to pass to MYSQLDUMP
	DESTDIR		The destination directory (required)
	CREATEDB	Include CREATE DATABASE statements (y/N)
_END
}

# Check configuration
# return: 0: ok, 1: error
do_check_conf()
{
	[ -z "$DATABASES" ] && h_error "Missing DATABASES" && return 1
	[ -z "$MYUSER" ] && h_error "Missing MYUSER" && return 1
	[ -z "$DESTDIR" ] && h_error "Missing DESTDIR" && return 1

	return 0
}

# Do backup
do_run()
{
	if [ "x$ABORT" = "x1" ] ; then
		return 0
	fi

	# Initialize
	if [ -z "$MYSQL" ] ; then
		MYSQL="mysql";
	fi

	if [ -z "$MYSQLDUMP" ] ; then
		MYSQLDUMP="mysqldump"
	fi

	if [ ! "$PASSWORD" = "" ] ;  then
		export MYSQL_PWD="$PASSWORD"
	fi


	for t in $MYSQL $MYSQLDUMP ; do
		if ! which $t > /dev/null ; then
			h_error "Could not find '$t'"
			return 1
		fi
	done

	P=""
	if [ ! -z "$CREATEDB" ] ; then
		# P="$P -B --create-options"
		P="$P --create-options"
	fi

	if [ "$DATABASES" = "-" ] ; then
		DATABASES=`$MYSQL -u $MYUSER --disable-pager --batch \
				-se 'show databases'`
		if ! [ "$?" = 0 ] ; then
			return 1
		fi
	fi

	ret=0
	for db in $DATABASES ; do
		h_msg 6 "Dumping: $db to $DESTDIR/$db.gz"
		if h_is_true $COMPRESS ; then
			$MYSQLDUMP -u $MYUSER -R $P $db \
				$MYSQLDUMPEXTRA \
				| gzip > "$DESTDIR/$db.gz"
		else
			$MYSQLDUMP -u $MYUSER -R $P $db \
				$MYSQLDUMPEXTRA \
				> "$DESTDIR/$db"
		fi
		if ! [ "$?" -eq 0 ] ; then
			h_msg 2 "Failed to backup $db"
			ret=1
		fi
	done

	return $ret
}


