#!/bin/bash
################################################################################
# Filename: ./src/base/sbin/admin/restore-db
# 
# The contents of this file are subject to the Qlusters Public License
# Version 1.1 (the License); you may not use this file except in compliance
# with the License.
# You may obtain a copy of the License at
# http://www.openqrm.org/content/view/33/69/.
# 
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
# 
# The Original Code is openQRM.
# 
# The Initial Developer of the Original Code is Qlusters Corporation. Portions
# created by Qlusters Corporation are Copyright (C) 2003-2005. All Rights
# Reserved.
# 
# Contributor(s):
# 
# Description:
# 
# Comments:
################################################################################
# restores the qrm-database from a backup-file

BASE_DIR=`dirname $0`
export QRM_SERVER_BASE_DIR=${QRM_SERVER_BASE_DIR:-`pushd $BASE_DIR/../../.. > /dev/null; echo $PWD; popd > /dev/null`}
. $QRM_SERVER_BASE_DIR/qrm/include/qrm-functions
. $QRM_SERVER_BASE_DIR/qrm/include/qrm-server-functions

if (( $# != "1" )); then
	echo "Usage : $0 <file>"
	exit 1
fi

echo "Starting QRM-server database restore"
DUMP_FILE=$1
# dump file exists already ?
if [ ! -f $DUMP_FILE ]; then
	echo "ERROR: QRM-server backup $DUMP_FILE does not exists."
	exit 1
fi
if /etc/init.d/qrm-server status | grep running 1>/dev/null; then
	echo "ERROR: QRM-server still running. Please stop the QRM-server and try again."
	exit 1
fi

qrm_get_server_config 1>/dev/null
# check for mysql
if which mysql 1>/dev/null 2>&1; then
        MYSQL_CLIENT=`which mysql`
elif [ ! -z "$MYSQL_HOME" ]; then
        MYSQL_CLIENT=$MYSQL_HOME/bin/mysql
elif [ ! -z "$QRM_DATABASE_HOME" ]; then
        MYSQL_CLIENT=$QRM_DATABASE_HOME/bin/mysql
else
        echo "ERROR: Mysql client 'mysql' not installed/found on this system"
        exit 1
fi
if [ ! -z "$QRM_DATABASE_PASSWORD" ]; then
	OPTIONAL_PASSWORD="--password=$QRM_DATABASE_PASSWORD"
fi
if ! $MYSQL_CLIENT -u $QRM_DATABASE_USER $OPTIONAL_PASSWORD --host=$QRM_DATABASE_SERVER -e "source $DUMP_FILE" qrm; then
	echo "ERROR: Could not restore the database content. Please check/fix the error above and try again."
	exit 1
fi
echo "Successfully restored the QRM-server-database from $DUMP_FILE"

