#!/bin/bash
# Copyright (C) 2008 Linagora Group.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.


obmconf=/etc/obm/obm-rpm.conf
echo -e "- Checking...\c"
MYSQL_SQL=`rpm -qa |grep obm-MySQL | cut -d"-" -f1-3`
echo -e "..OK"

. ${obmconf}

DB="MySQL"
# Check if MySQL server is running
/sbin/service mysqld status %2>/dev/null	
if [ "$?" -gt "0" ] ; then
	/sbin/service mysqld start %2>/dev/null
fi
echo -e "\n"
echo -e "Enter root Mysql Password :\c"
read passwd
if [ -z ${passwd} ] ; then
	MYSQL_CMD="/usr/bin/mysql -h ${OBM_HOST}"
else
	MYSQL_CMD="/usr/bin/mysql -h ${OBM_HOST} -u root -p$passwd"
fi

# Check if database already exist
CHECKDB=`${MYSQL_CMD} -e "SHOW DATABASES"| grep ${OBM_DBNAME}`
#echo -e "- Checking...."
if [ "$CHECKDB" = "${OBM_DBNAME}" ] ; then
	echo "WARNING: DataBase ${OBM_DBNAME} already exist"
	echo -e "o Would you like to overise ${OBM_DBNAME} DataBase : (y)es (n)o ? \c"
	read answear
        if [ ${answear} = "y" -o ${answear} = "yes" ] ; then
        	# Drop present database (outch!)
		echo -e "- Overised.....\c"
		sleep 1
                $MYSQL_CMD -e "DROP DATABASE ${OBM_DBNAME}" && echo -e "OK"
	else
		echo -e "\n"
		echo "So then, choose another Database name in obm-config before continue."
		exit 0
	fi
fi

# Create DataBase 
echo -e "- Creating OBM DataBase.....\c"
sleep 1
$MYSQL_CMD -e "CREATE DATABASE ${OBM_DBNAME}" && echo -e "OK"
# Add user to DataBase
echo -e "- Adding OBM user.....\c"
sleep 1
$MYSQL_CMD -e "GRANT ALL PRIVILEGES ON ${OBM_DBNAME}.* TO '${OBM_DBUSER}'@'${OBM_HOST}' IDENTIFIED BY '$OBM_PASSWD' WITH GRANT OPTION" && echo -e "OK"
	
echo -e "- Installing SQL schemas.....\c"
sleep 2
$MYSQL_CMD ${OBM_DBNAME} < /usr/share/doc/$MYSQL_SQL/mysql.sql && echo -e "OK"

exit 0

