@echo off

rem ##############################################################################
rem #
rem # Copyright (c) 2013 VMware, Inc. All rights reserved.
rem # -- VMware Confidential
rem #
rem ##############################################################################

set _LOGBROWSER_SC_EXE=%windir%\system32\sc.exe
set _LOGBROWSER_XCOPY_EXE=%windir%\system32\xcopy.exe

call "%~dp0common" Verifying that required tools are installed

if NOT EXIST "%_LOGBROWSER_SC_EXE%" (
    set last_error=sc.exe is not present in the system32 directory.
    goto endError
)

if NOT EXIST "%_LOGBROWSER_XCOPY_EXE%" (
    set last_error=xcopy.exe is not present in the system32 directory.
    goto endError
)

rem check JAVA_HOME
if "%JAVA_HOME%" == "" (
    set last_error=JAVA_HOME environment variable is not set
    goto endError
)

rem check sso admin credentials
if "%sso_admin_user%"=="" (
    set last_error=The Single Sign-On Administrator user was not specified
    goto endError
)
if "%sso_admin_password%"=="" (
    set last_error=The Single Sign-On Administrator password was not specified
    goto endError
)

rem retrieve ngc installation directory from the registry
set _LOGBROWSER_NGC_REG_PATH="HKLM\SOFTWARE\VMware, Inc.\VMware Infrastructure\vSphere Web Client"
set _LOGBROWSER_NGC_INSTALL_PATH=
for /f "tokens=1,2*" %%a in ('reg query %_LOGBROWSER_NGC_REG_PATH% /v "InstallPath"') do (
   if "%%a"=="InstallPath" (
      set "_LOGBROWSER_NGC_INSTALL_PATH=%%c"
   )
)
if "%_LOGBROWSER_NGC_INSTALL_PATH%"=="" (
    call "%~dp0common" Failed to retrieve the vSphere Web Client path from the registry. Log Browser might not be installed.
    exit /B 2
)
rem chop off the last backslash if one is present
if "%_LOGBROWSER_NGC_INSTALL_PATH:~-1%" == "\" set "_LOGBROWSER_NGC_INSTALL_PATH=%_LOGBROWSER_NGC_INSTALL_PATH:~0,-1%"
call "%~dp0common" Successfully retrieved the vSphere Web Client path from the registry "%_LOGBROWSER_NGC_INSTALL_PATH%"

rem use the rollback folder as a temporary folder
set "_LOGBROWSER_TEMP_FOLDER=%ROLLBACK_BACKUP_FOLDER%"
rem validating and setting LOGBROWSER TEMP FOLDER
rem chop off the last backslash if one is present
if "%_LOGBROWSER_TEMP_FOLDER:~-1%" == "\" set "_LOGBROWSER_TEMP_FOLDER=%_LOGBROWSER_TEMP_FOLDER:~0,-1%"
call "%~dp0common" Temporary folder is "%_LOGBROWSER_TEMP_FOLDER%"
if NOT EXIST "%_LOGBROWSER_TEMP_FOLDER%" (
    mkdir "%_LOGBROWSER_TEMP_FOLDER%"
    if NOT EXIST "%_LOGBROWSER_TEMP_FOLDER%" (
        set last_error=Specified temporary folder "%_LOGBROWSER_TEMP_FOLDER%" does not exist.
        goto endError
    )
)
set "_LOGBROWSER_TEMP_FOLDER=%_LOGBROWSER_TEMP_FOLDER%\logbrowser"
if NOT EXIST "%_LOGBROWSER_TEMP_FOLDER%" (
    mkdir "%_LOGBROWSER_TEMP_FOLDER%"
)
call "%~dp0common" LogBrowser temporary folder is "%_LOGBROWSER_TEMP_FOLDER%"
if NOT EXIST "%_LOGBROWSER_TEMP_FOLDER%" (
    set last_error=Log Browser temporary folder "%_LOGBROWSER_TEMP_FOLDER%" does not exist.
    goto endError
)

rem retrieve lookup service URL
set _LOGBROWSER_LS_URL=
for /F "usebackq tokens=1,2*" %%i in (`reg query %_LOGBROWSER_NGC_REG_PATH% /v "LsUrl"`) DO (
   if "%%i"=="LsUrl" (
      set "_LOGBROWSER_LS_URL=%%k"
   )
)
if "%_LOGBROWSER_LS_URL%"=="" (
   set last_error=Failed to retrieve the Lookup Service URL from the registry
   goto endError
)
call "%~dp0common" Successfully retrieved the Lookup Service URL from the registry "%_LOGBROWSER_LS_URL%"
rem validate LS connection, validate credentials
set "_LOGBROWSER_REG_TOOL_CMD=%_LOGBROWSER_NGC_INSTALL_PATH%\SsoRegTool\regTool.cmd"
call "%~dp0common" Validating Lookup Service connection
call "%_LOGBROWSER_REG_TOOL_CMD%" validateLsConnection --cert "%_LOGBROWSER_TEMP_FOLDER%" --ls-url "%_LOGBROWSER_LS_URL%" --username "%sso_admin_user%" --password "%sso_admin_password%"
if NOT "%ERRORLEVEL%"=="0" (
   set last_error=Cannot validate the Lookup Service connection - error code is %ERRORLEVEL%
   goto endError
)

rem if this script was invoked from logbrowser-update-ssl, we only need to unregister/register Logbrowser
if "%1"=="-logbrowser-update-ssl" (
    goto unregister_and_register_LbToSsoAndLk
)

set "_LOGBROWSER_SSL_PATH=%_LOGBROWSER_NGC_INSTALL_PATH%\logbrowser\conf"
rem validate if we can locate LogBrowser SSL directory
if NOT EXIST "%_LOGBROWSER_SSL_PATH%" (
    set last_error=Unable to locate LogBrowser certificate directory "%_LOGBROWSER_SSL_PATH%"
    goto endError
)

rem check if the Log Browser properties file is in place
if NOT EXIST "%_LOGBROWSER_SSL_PATH%\logbrowser.properties" (
    set last_error=Cannot find the Log Browser server properties file "%_LOGBROWSER_SSL_PATH%\logbrowser.properties"
    goto endError
)

rem check which version of Logbrowser is installed in this machine (5.1.0 or later)
set _LOGBROWSER_VERSION=
For /F "usebackq tokens=1* delims==" %%G IN ("%_LOGBROWSER_SSL_PATH%\logbrowser.properties") DO (
    if "%%G"=="lb-vsphere-version" (
        set "_LOGBROWSER_VERSION=%%H"
    )
)
call "%~dp0common" The Logbrowser version installed in this machine is vSphere-"%_LOGBROWSER_VERSION%"
if "%_LOGBROWSER_VERSION%"=="" (
    rem the first version of Logbrowser (vSphere-5.1.0) does not have the lb-vsphere-version field
    goto retrieve_trusted_certificates
)
rem ELSE:
rem ##############################################################################
rem # we are dealing with a version greater than vSphere-5.1.0, such as 5.1.1 or 5.5.0
rem # we need to extract the root CA certificate from the SSO certificate chain and append into ca_certificates.crt file
rem # as VC is already doing at vc-update-trust-to-sso.bat
rem ##############################################################################

set _LOGBROWSER_VC_REG_KEY="HKLM\SOFTWARE\VMware, Inc.\VMware VirtualCenter"
set _LOGBROWSER_VC_REG_EXE=%windir%\system32\reg.exe
set "_LOGBROWSER_VC_UPDATE_TRUST_BAT=%~dp0vc-update-trust-to-sso.bat"
rem check if VC is installed on the same machine
set _LOGBROWSER_VC_INSTALL_DIR=
call :getVCInstallDir > nul 2>&1
if NOT "%_LOGBROWSER_VC_INSTALL_DIR%"=="" (
    call "%~dp0common" vCenter it is installed at this machine, so the root CA certificate is already appended into ca_certificates.crt file
    goto unregister_and_register_LbToSsoAndLk
)
rem ELSE: vCenter it is _not_ installed at this machine
call "%~dp0common" vCenter it is not installed at this machine
call "%~dp0common" Invoking vc-update-trust-to-sso.bat to append the root CA certificate into ca_certificates.crt file
call "%_LOGBROWSER_VC_UPDATE_TRUST_BAT%" -logbrowser-update-trust
if NOT "%ERRORLEVEL%"=="0" (
  set last_error=Cannot append the root CA certificate into ca_certificates.crt file, error code is "%ERRORLEVEL%"
  goto endError
)
call "%~dp0common" Successfully appended the root CA certificate into ca_certificates.crt file
rem ELSE: if VC is installed in the same machine as Logbrowser we can assume that the script vc-update-trust-to-sso.bat was already invoked
goto unregister_and_register_LbToSsoAndLk

rem ##############################################################################
rem # vSphere-5.1.0 only: Retrieve trusted certificates, write on trusted_certificates.crt and make LogBrowser points to it
rem ##############################################################################
:retrieve_trusted_certificates
call "%~dp0common" Retrieve trusted certificates

rem stop LogBrowser, because we are going to edit trusted_certificates.crt and logbrowser.properties files
set _STOP_LOGBROWSER_ERROR_MSG=
call :stopLogbrowser 2>&1
if NOT "%_STOP_LOGBROWSER_ERROR_MSG%"=="" (
    set last_error=%_STOP_LOGBROWSER_ERROR_MSG%
    goto endError
)

if EXIST "%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt" del /F "%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt"

rem retrieve trusted certificates from sso-admin
set "_LOGBROWSER_SSL_TOOL_JAR=%~dp0logbrowser-updater.jar"
"%JAVA_HOME%\bin\java" -jar "%_LOGBROWSER_SSL_TOOL_JAR%" --ls-url "%_LOGBROWSER_LS_URL%" --output-cert-file "%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt"
if ERRORLEVEL 1 (
    set last_error=Cannot retrieve trusted certificates from Single Sign-On-Admin
    goto endError
)
call "%~dp0common" Successfully retrieved the trusted certificates from Single Sign-On-Admin, look at "%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt"

rem create an empty temporary properties file
IF EXIST "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties" del /F "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties"
echo. 2>"%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties"

rem replace single backslash to double backslash
set "cert_path_with_double_backslash=%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt"
set "cert_path_with_double_backslash=%cert_path_with_double_backslash:\=\\%"

rem copying content of current logbrowser.properties to a temp file in order to update logbrowser.properties to point to the trusted_certificates.crt file
For /F "usebackq tokens=1* delims==" %%G IN ("%_LOGBROWSER_SSL_PATH%\logbrowser.properties") DO (
    if "%%G"=="sso-certs" (
        echo %%G=%cert_path_with_double_backslash%>> "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties"
    ) else (
        echo %%G=%%H>> "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties"
    )
)
call "%~dp0common" Successfully created the logbrowser_temp.properties file, which points to the trusted certifites "%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt"

rem replace the current logbrowser.properties file with the temporary file (logbrowser_temp.properties) that was previously edited
"%_LOGBROWSER_XCOPY_EXE%" /y "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties" "%_LOGBROWSER_SSL_PATH%\logbrowser.properties"
if ERRORLEVEL 1 (
    set last_error=Cannot copy "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties" to "%_LOGBROWSER_SSL_PATH%\logbrowser.properties": %ERRORLEVEL%
    goto endError
)
call "%~dp0common" Successfully replaced "%_LOGBROWSER_TEMP_FOLDER%\logbrowser_temp.properties" with "%_LOGBROWSER_SSL_PATH%\logbrowser.properties"

call "%~dp0common" Log Browser server is now using the trusted certificates retrieve from Single Sign-On-Admin, which is now located under "%_LOGBROWSER_SSL_PATH%\trusted_certificates.crt" instead of using the default location "PROGRAMDATA\VMware\SSL\ca_certificates.crt"

rem ##############################################################################
rem # Unregister and Register LogBrowser with SSO and Lookup Service
rem ##############################################################################
:unregister_and_register_LbToSsoAndLk
call "%~dp0common" Re-register Logbrowser with Single Sign-On-Admin and Lookup Service

set "_LOGBROWSER_NGC_SERVICE_ID_FILE=%_LOGBROWSER_NGC_INSTALL_PATH%\serviceId"
set "_LOGBROWSER_SOLUTION_FILE=%_LOGBROWSER_NGC_INSTALL_PATH%\SsoRegTool\sso_conf\solution.ini"

if NOT EXIST "%_LOGBROWSER_SOLUTION_FILE%" (
   set last_error=Cannot find the Log Browser solution file "%_LOGBROWSER_SOLUTION_FILE%"
   goto endError
)
rem retrieve solution username as means of unregister/register Log Browser from SSO
For /F "usebackq tokens=1* delims==" %%A IN ("%_LOGBROWSER_SOLUTION_FILE%") DO (
    IF "%%A"=="name" set _LOGBROWSER_SOLUTION_USERNAME=%%B
)
if "%_LOGBROWSER_SOLUTION_USERNAME%"=="" (
    set last_error=Unable to read solution-username from "%_LOGBROWSER_SOLUTION_FILE%"
    goto endError
)
call "%~dp0common" Successfully read solution-username "%_LOGBROWSER_SOLUTION_USERNAME%"

rem stop LogBrowser
set _STOP_LOGBROWSER_ERROR_MSG=
call :stopLogbrowser 2>&1
if NOT "%_STOP_LOGBROWSER_ERROR_MSG%"=="" (
    set last_error=%_STOP_LOGBROWSER_ERROR_MSG%
    goto endError
)

rem if service-id file does not exist, LogBrowser is already unregistered from Lookup Service
if NOT EXIST "%_LOGBROWSER_NGC_SERVICE_ID_FILE%" (
    call "%~dp0common" service-id file does not exist, LogBrowser is already unregistered from Lookup Service
    goto unregisterSSO
)

rem unregister LogBrowser from Lookup Service
call "%~dp0common" Unregistering Log Browser from Lookup Service
call "%_LOGBROWSER_REG_TOOL_CMD%" unregisterService -si "%_LOGBROWSER_NGC_SERVICE_ID_FILE%" -d "%_LOGBROWSER_LS_URL%" -u "%sso_admin_user%" -p "%sso_admin_password%"
if "%ERRORLEVEL%"=="8" (
   call "%~dp0common" Skipping the unregistration from Lookup Service
   goto unregisterSSO
)
if NOT "%ERRORLEVEL%"=="0" (
   set last_error=Cannot unregister Log Browser from Lookup Service - errorlevel is %ERRORLEVEL%
   goto endError
)

:unregisterSSO
rem unregister LogBrowser from SSO using _LOGBROWSER_SOLUTION_USERNAME
call "%~dp0common" Unregistering Log Browser from Single Sign-On
call "%_LOGBROWSER_REG_TOOL_CMD%" unregisterSolution -su "%_LOGBROWSER_SOLUTION_USERNAME%" -d "%_LOGBROWSER_LS_URL%" -u "%sso_admin_user%" -p "%sso_admin_password%"
if "%ERRORLEVEL%"=="8" (
   call "%~dp0common" Skipping unregistration from Single Sign-On
   goto reRegisterLBToSsoAndLk
)
if NOT "%ERRORLEVEL%"=="0" (
   set last_error=Cannot unregister Log Browser from Single Sign-On - errorlevel is %ERRORLEVEL%
   goto endError
)

:reRegisterLBToSsoAndLk
rem delete service ID file (if exist)
IF EXIST "%_LOGBROWSER_NGC_SERVICE_ID_FILE%" del /F "%_LOGBROWSER_NGC_SERVICE_ID_FILE%"

rem re-register LogBrowser with SSO
call "%~dp0common" Re-registering Log Browser with Single Sign-On
call "%_LOGBROWSER_REG_TOOL_CMD%" registerSolution -d "%_LOGBROWSER_LS_URL%" -ip "%_LOGBROWSER_SOLUTION_FILE%" -r read -u "%sso_admin_user%" -p "%sso_admin_password%"
if "%ERRORLEVEL%"=="7" (
    call "%~dp0common" LogBrowser service is already registered with Single Sign-On
)
if "%ERRORLEVEL%"=="6" (
    set last_error=Cannot register Log Browser with Single Sign-On
    goto endError
)
if ERRORLEVEL 1 (
    set last_error=Cannot register Log Browser with Single Sign-On - errorlevel is %ERRORLEVEL%
    goto endError
)

rem re-register LogBrowser with Lookup Service
call "%~dp0common" Re-registering Log Browser with Lookup Service
call "%_LOGBROWSER_REG_TOOL_CMD%" registerService -d "%_LOGBROWSER_LS_URL%" -dir "%_LOGBROWSER_NGC_INSTALL_PATH%\SsoRegTool\sso_conf" -ip "*.*" -o -si "%_LOGBROWSER_NGC_SERVICE_ID_FILE%" -u "%sso_admin_user%" -p "%sso_admin_password%"
if "%ERRORLEVEL%"=="7" (
    call "%~dp0common" LogBrowser service is already registered with Lookup Service
)
if "%ERRORLEVEL%"=="6" (
    set last_error=Cannot register Log Browser with Lookup Service
    goto endError
)
if ERRORLEVEL 1 (
    set last_error=Cannot register Log Browser with Lookup Service - errorlevel is %ERRORLEVEL%
    goto endError
)

rem start Log Browser
"%_LOGBROWSER_SC_EXE%" start vmwarelogbrowser > nul
if ERRORLEVEL 1 (
    set last_error=Cannot start the Log Browser service - error code is %ERRORLEVEL%
    goto endError
)

:endSuccess
call "%~dp0common" Successfully updated the Log Browser trust to Single Sign-On
exit /B 0

:endError
rem making sure that Logbrowser is on the START state even in a case of failure
"%_LOGBROWSER_SC_EXE%" start vmwarelogbrowser > nul
if ERRORLEVEL 1 (
    call "%~dp0common" Cannot start the Log Browser service - error code is %ERRORLEVEL%
)
call "%~dp0common" "%last_error%"
call "%~dp0common" Error - Operation failed
exit /B 1

:getVCInstallDir
set _LOGBROWSER_VC_INSTALL_DIR=
for /F "usebackq tokens=1,2*" %%i in (`%_LOGBROWSER_VC_REG_EXE% query %_LOGBROWSER_VC_REG_KEY% /v "InstallPath"`) DO (
   if "%%i"=="InstallPath" (
      SET "_LOGBROWSER_VC_INSTALL_DIR=%%k"
   )
)
exit /B 0

:stopLogbrowser
call "%~dp0common" Stopping Log Browser
:loop_pending_stop
"%_LOGBROWSER_SC_EXE%" stop vmwarelogbrowser > nul
"%_LOGBROWSER_SC_EXE%" stop vmwarelogbrowser > nul
if "%ERRORLEVEL%"=="1062" (
    call "%~dp0common" The Log Browser is already stopped
    exit /B
)
if "%ERRORLEVEL%"=="1061" (
    call "%~dp0common" Pending Log Browser stop
    timeout /t 5 /nobreak > nul
    goto loop_pending_stop
)
if ERRORLEVEL 1 (
    set "_STOP_LOGBROWSER_ERROR_MSG=Failed to stop Log Browser: %ERRORLEVEL%"
    exit /B
)
call "%~dp0common" The Log Browser service is stopped
exit /B
