@echo off

REM Inicialitzem les variables
set PORT=
set DEBUG=
set KEYSTONE_PATH=
set KEYSTORE_PASSWORD=
set KEYSTORE_TYPE=
set KEY_ALIAS=
set KEY_PASSWORD=
set J_DEBUG=

REM Parsegem els paràmetres
:parse_args
if "%~1"=="" goto args_done

if "%~1"=="-p" (
    set PORT=%2
    shift
) else if "%~1"=="-d" (
    set DEBUG=true
    shift
) else if "%~1"=="-ks" (
    set KEYSTONE_PATH=%2
    shift
) else if "%~1"=="-kp" (
    set KEYSTORE_PASSWORD=%2
    shift
) else if "%~1"=="-ka" (
    set KEY_ALIAS=%2
    shift
) else if "%~1"=="-kk" (
    set KEY_PASSWORD=%2
    shift
) else if "%~1"=="-kt" (
    set KEYSTORE_TYPE=%2
    shift
) else if "%~1"=="-jpda" (
    set J_DEBUG=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=%2
    shift
) else if "%~1"=="-jmx" (
    set J_JMX=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=%2 -Dcom.sun.management.jmxremote.rmi.port=%2 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
    shift
)

shift
goto parse_args

:args_done

REM Validem els parametres rebuts
if defined PORT (
    if not "%PORT%" geq "7000" if not "%PORT%" leq "65535" (
        echo Error: El número de port ha de ser un número entre 7000 i 65535.
        exit /b 1
    )
)

if defined DEBUG (
    if /i not "%DEBUG%"=="true" (
        echo Error: El flag de debug ha de tenir el valor 'true'.
        exit /b 1
    )
)

if defined KEYSTONE_PATH (
    if not exist "%KEYSTONE_PATH%" (
        echo Error: El fitxer a la ruta especificada per al keystone no existeix.
        exit /b 1
    )
)

if defined KEYSTORE_TYPE (
    if /i not "%KEYSTORE_TYPE%"=="JKS" if /i not "%KEYSTORE_TYPE%"=="PKCS12" (
        echo Error: El tipus de keystore ha de ser 'JKS' o 'PKCS12'.
        exit /b 1
    )
)


REM Invoquem la aplicacio Java
set JAVA_OPTS=

if defined J_DEBUG (
	set JAVA_OPTS=%JAVA_OPTS% %J_DEBUG%
)

if defined J_JMX (
	set JAVA_OPTS=%JAVA_OPTS% %J_JMX%
)

if defined DEBUG (
    if /i "%DEBUG%"=="true" (
		set JAVA_OPTS=%JAVA_OPTS% -Dmorena.debug=true
    ) else if /i "%DEBUG%"=="false" (
		set JAVA_OPTS=%JAVA_OPTS% -Dmorena.debug=false
	)
)

if defined PORT (
	set JAVA_OPTS=%JAVA_OPTS% -Dbridge.module.port=%PORT%
)

if defined KEYSTONE_PATH (
 	set JAVA_OPTS=%JAVA_OPTS% -Dbridge.module.server.cert.keystore.path=%KEYSTONE_PATH%
)

if defined KEYSTORE_TYPE (
	set JAVA_OPTS=%JAVA_OPTS% -Dbridge.module.server.cert.keystore.type=%KEYSTORE_TYPE%
)

if defined KEY_ALIAS (
 	set JAVA_OPTS=%JAVA_OPTS% -Dbridge.module.server.cert.keystore.alias=%KEY_ALIAS%
)

if defined  KEYSTORE_PASSWORD (
 	set JAVA_OPTS=%JAVA_OPTS% -Dbridge.module.server.cert.keystore.pin=%KEYSTORE_PASSWORD%
)

if defined KEY_PASSWORD (
	set JAVA_OPTS=%JAVA_OPTS% -Dbridge.module.server.cert.keystore.key.password=%KEY_PASSWORD%
)

set JAVA_HOME=.\java8

%JAVA_HOME%\bin\java -cp lib/*;scanner-bridge.jar %JAVA_OPTS% cat.aoc.scanner.bridge.ScannerBridge

:END