#!/bin/sh
# createemgdb-mysql.sh
#
# Sample script for creating an EMG database
# in a local MySQL database server.
#
# Please verify carefully that the username,
# password and database information below is
# correct for your installation.
#
# SCRIPT PROVIDED AS IS.
# TO BE USED AT OWN RISK.

admuser=root
emgdb=emg
emguser=emguser
emgpasswd=secret
#host="-h127.0.0.1"
#port="-P3306"

scriptdir=`dirname $0`

while [ $# -gt 1 ]; do
	isok=0
#	echo arg: $1
	[ x$1 = x--pw ] && {
		[ $# -gt 0 ] || {
			echo "Missing arg to --pw."
			exit 1
		}
		shift
		emgpasswd="$1"
		isok=1
	}
	[ $isok = 0 ] && {
		echo Invalid argument: $1
		exit 1
	}
	shift
done

cmd=$1

[ "$emgpasswd" = "secret" ] && {
	echo
	echo "ERROR!!!"
	echo "Have you checked parameters in script?"
	echo "You need to edit this script and at least change the db password in variable \"emgpasswd\" on line 17."
	echo "We recommend creating a strong password with a password generator."
	echo "Do not forget to write it down and store it in a safe place."
	echo
	exit 1
}

[ "$cmd" = "" ] && {
	echo "Please supply an operation:"
	echo "createdb"
	echo "dropdb"
	exit 1
}

mysqladmincmd="mysql $host $port -u$admuser -p mysql"
mysqlusercmd="mysql $host $port -u$emguser -p$emgpasswd $emgdb"

case $cmd in
createdb)
	echo "Creating the EMG database and the '$emguser' user."
	echo "MySQL will prompt for the MySQL root password."

	# Create database and user
	$mysqladmincmd <<EOF
DROP DATABASE IF EXISTS $emgdb;
DROP USER IF EXISTS '$emguser'@'%';
DROP USER IF EXISTS '$emguser'@'127.0.0.1';
DROP USER IF EXISTS '$emguser'@'localhost';
CREATE DATABASE $emgdb CHARACTER SET utf8;
CREATE USER $emguser@127.0.0.1 IDENTIFIED BY '$emgpasswd';
CREATE USER $emguser@"%" IDENTIFIED BY '$emgpasswd';
GRANT ALL PRIVILEGES ON $emgdb.* TO $emguser@127.0.0.1, $emguser@"%";
FLUSH PRIVILEGES
EOF
	echo "Creating tables..."
	$mysqlusercmd < $scriptdir/emg-schema-mysql.sql
	echo "Adding data to the tables..."
	$mysqlusercmd < $scriptdir/initdbconfig.sql
	;;

dropdb)
	echo "Dropping the EMG database..."
	$mysqlusercmd <<EOF
DROP DATABASE IF EXISTS $emgdb;
EOF
	echo "Deleting the '$emguser' user."
	echo "MySQL will prompt for the MySQL root password."
	$mysqladmincmd <<EOF
DROP USER IF EXISTS '$emguser';
EOF
	;;
esac

[ "$?" != "0" ] && {
	echo "failed!"
	exit 1
}

echo "OK"

exit 0

