@echo off
@rem ------------------------------------------------------------------------------
@rem Company: Software- und Organisations-Service GmbH
@rem Purpose: Script to encrypt using public key or X509 certificate
@rem ------------------------------------------------------------------------------

@rem Example
@rem call .\bin\js7_encrypt.cmd "--cert=agent.crt" "--in=secret"

if defined JAVA (
  set JAVA_EXE=%JAVA%
) else (
  set JAVA_EXE=%JAVA_HOME%\bin\java.exe
)

if exist "%JAVA_EXE%" (
  call :set_java_exe "%JAVA_EXE%"
) else (
  set JAVA_EXE=java.exe
)
set JS7_ENCRYPT_LIBDIR=%~dp0..\lib
set CP=%JS7_ENCRYPT_LIBDIR%/patches/*;%JS7_ENCRYPT_LIBDIR%/sos/*;%JS7_ENCRYPT_LIBDIR%/3rd-party/*;%JS7_ENCRYPT_LIBDIR%/stdout
set JS7_ENCRYPT_VALUE_ERROR=0

if "%~1"=="" goto help
if "%~1"=="-h" goto help
if "%~1"=="--help" goto help

for /f "usebackq tokens=1*" %%A in (`%JAVA_EXE% -classpath "%CP%" com.sos.commons.encryption.executable.Encrypt %* ^|^| call echo SOS_ERROR_%%^^ERRORLEVEL%%`) do (
       if "%%~A"=="SOS_ERROR_1" (
           goto set_error_1
       )
       if "%%~A"=="SOS_ERROR_2" (
              goto set_error_2
       )
       if "%%~B"=="" (
           call :set_result "%%~A"
       ) else (
           call :set_result "%%~A %%~B"
       )
)

goto finally

:help
%JAVA_EXE% -classpath "%CP%" com.sos.commons.encryption.executable.Encrypt --help
goto finally

:set_java_exe
set JAVA_EXE=%~s1
goto final

:set_error_1
set JS7_ENCRYPT_VALUE_ERROR=1
goto finally

:set_error_2
set JS7_DECRYPT_VALUE_ERROR=2
goto finally

:set_result
set JS7_ENCRYPT_VALUE=%~1
goto finally

:finally
exit /b %JS7_ENCRYPT_VALUE_ERROR%
:final
