:: This batch file is used to create the g2 repository instance and the actual database containing the repository.
:: %1 GNR data path
:: %2 G2 templates path
:: %3 G2 repositories parent path
:: %4 G2 repository instance name
:: %5 port number
:: %6 username
:: %7 password

::Goto Base Folder
CD /D %3
IF ERRORLEVEL 1 GOTO NO_BASE_FOLDER

:: Make folder for new respository
MKDIR %4
IF ERRORLEVEL 1 GOTO ALREADY_EXISTS

:: Go into the new respository folder.
CD %4

MKDIR logs

:: Copy needed files.
COPY %2\g2.ini .
COPY %2\map.xml
COPY %2\g2_db2_schema.sql


::Replace the placeholder with corresponding content.
CSCRIPT %2\replace.vbs g2.ini {Port} %5
CSCRIPT %2\replace.vbs g2.ini {DataFolder} %1
CSCRIPT %2\replace.vbs g2.ini {UserName} %6 {Password} %7
CSCRIPT %2\replace.vbs g2.ini {Database} %4


:: create database and populate the schema
IF "%DB2NODENAME%" == "" ( goto :Local ) 
goto :remote

:Local
echo "local"
db2cmd /c /w /i "db2start & db2 create database %4 & db2 connect to %4 user '%6' using '%7' & db2 -tvf g2_db2_schema.sql" 
IF "%ERRORLEVEL%" == "0" ( goto :createEnd )
IF "%ERRORLEVEL%" == "1" ( goto :createEnd )
goto :errorCreate

:remote
db2cmd /c /w /i "db2 attach to %DB2NODENAME% user '%6' using '%7' & db2 create database %4 & db2 connect to %4 user '%6' using '%7' & db2 -tvf g2_db2_schema.sql" 
IF "%ERRORLEVEL%" == "0" ( goto :createEnd )
IF "%ERRORLEVEL%" == "1" ( goto :createEnd )
goto :errorCreate

:createEnd
DEL g2_db2_schema.sql

GOTO END

:ALREADY_EXISTS
Echo Repository already exists.
Exit /B 1

:NO_BASE_FOLDER
Echo Base folder not exists.
Exit /B 2

:errorCreate
Echo Error create repository.
Exit /B 105

:END
Echo finished.