#!/bin/bash

USER="root"
PASSWORD="1000omc@kp!"
PORT="33066"
DBNAME="omc_db"
UpgradeSQLDir=/usr/local/omc/etc/db/upgrade
InstallSQLDir=/usr/local/omc/etc/db/install

drop_db_sql="drop database IF EXISTS ${DBNAME}"
create_db_sql="create database IF NOT EXISTS ${DBNAME}"

case "$1" in
        upgrade)
			echo "Upgrade database ${DBNAME}"
			for SQL in ${UpgradeSQLDir}/*.sql; do 
				echo "Execute SQL script: ${SQL} ..."
				mysql -u${USER} -p${PASSWORD} -P ${PORT} -D ${DBNAME} < ${SQL}; 
			done
        ;;
        install)
			echo "Drop database ${DBNAME} ...!!!"
		    mysql -u${USER} -p${PASSWORD} -P $PORT -e "${drop_db_sql}"
			echo "Create database ${DBNAME} if not exist"
			mysql -u${USER} -p${PASSWORD} -P $PORT -e "${create_db_sql}"
			for SQL in ${InstallSQLDir}/*.sql; do 
				echo "Execute SQL script: ${SQL} ..."
				mysql -u${USER} -p${PASSWORD} -P ${PORT} -D ${DBNAME} < ${SQL}; 
			done
        ;;
        *)
			while true
			do
				read -r -p "Do you upgrade or fresh install database ${DBNAME}? [Upgrade/Install/Quit] " input

				case $input in
				    [uU][pP][gG][rR][aA][dD][eE]|[uU])
						echo "Skip to drop database ${DBNAME}"

						for SQL in ${UpgradeSQLDir}/*.sql; do 
							echo "Execute SQL script: ${SQL} ..."
							mysql -u${USER} -p${PASSWORD} -P ${PORT} -D ${DBNAME} < ${SQL}; 
						done

			            break
						;;

				    [iI][nN][sS][tT][aA][lL][lL]|[iI])
			            echo "Drop database ${DBNAME} ...!!!"

			            mysql -u${USER} -p${PASSWORD} -P $PORT -e "${drop_db_sql}"
						echo "Create database ${DBNAME} if not exist"
						mysql -u${USER} -p${PASSWORD} -P $PORT -e "${create_db_sql}"

						for SQL in ${InstallSQLDir}/*.sql; do 
							echo "Execute SQL script: ${SQL} ..."
							mysql -u${USER} -p${PASSWORD} -P ${PORT} -D ${DBNAME} < ${SQL}; 
						done

			            break           
						;;

				    [qQ][uU][iI][tT]|[qQ])
						echo "Nothing to be done! GOOD BYE"
			            exit 1;
						;;

				    *)
						echo "Invalid input..."
						;;
				esac
			done
        ;;
esac 




