@echo off
cd $MYSQL_PATH\bin

rem set login and password
set LOGIN=--user=$MYSQL_LOGIN
set PASS=$MYSQL_PASSWORD
set DBNAME=$DB_NAME
set PORT=--port=$MYSQL_PORT

@if not "%PASS%" == "" set PASS=--password=%PASS%

set /a i=0

:connect
echo Try to establish connection to MySQL service...
set /a i=i+1
mysql %LOGIN% %PASS% %PORT% < .\sql\connect.sql > null

if "%i%" == "40" goto invalid
 
if errorlevel 1 goto connect

echo Connected Successfully.

if "$DB_ACTION" == "CREATE" goto db_creation
if "$DB_ACTION" == "UPDATE" goto db_updating
if "$DB_ACTION" == "NONE"   goto sql_deletion

:db_updating
echo Updating existing QueWeb database...

set LOGIN=--user=$DB_USER
set PASS=--password=$DB_PASSWORD

mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\v068_to_v076.sql > null
echo SQL Script 1 of 2 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\v055_to_v057.sql > null
echo SQL Script 2 of 2 executed successfully.

goto sql_deletion 

:db_creation

echo Creating a new QueWeb database ...
mysql %LOGIN% %PASS% %PORT% < .\sql\0.database-qwoss_v001.sql > null
echo SQL Script 1 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\0.database-qwoss-login_v001.sql > null
echo SQL Script 2 of 11 executed successfully.

set LOGIN=--user=$DB_USER
set PASS=--password=$DB_PASSWORD

mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\1.framework-objects_v076.sql > null
echo SQL Script 3 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\2.framework-sp_v001.sql > null
echo SQL Script 4 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\3.framework-data_v076.sql > null
echo SQL Script 5 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\4.primarykeys-update_proc_v001.sql > null
echo SQL Script 6 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\5.framework-data_v057.sql > null
echo SQL Script 7 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\6.dataschema_v057.sql > null
echo SQL Script 8 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\7.data-dictionaries_v056.sql > null
echo SQL Script 9 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\8.application-data_v056.sql > null
echo SQL Script 10 of 11 executed successfully.
mysql %LOGIN% %PASS% %PORT% %DBNAME% < .\sql\mail_settings.sql > null
echo SQL Script 11 of 11 executed successfully.
echo MySQL QueWeb database has been successfully created.

goto sql_deletion

:sql_deletion

echo Removing temporary SQL script files...
rem remove sql files
del .\sql /Q /F
rmdir .\sql
echo All temporary SQL script files have been removed.

goto exit

:invalid
echo Connect was not established, please check that MySQL is installed and started!

:exit