@echo off

rem ##############################################################################
rem #
rem # Copyright (c) 2013 VMware, Inc. All rights reserved.
rem # -- VMware Confidential
rem #
rem ##############################################################################
rem system variables
set SCRIPT_NAME=ssl-updater
set SCRIPT_DESCRIPTION=This script updates SSL certificates
set SCRIPT_VERSION=1.0.0
set SCRIPT_COPYRIGHT=Copyright (c) 2013 VMware, Inc.

rem first set the environment variables
call "%~dp0ssl-environment.bat"

if "%ProgramFiles(x86)%"=="%ProgramFiles%" (
   rem Appear to be a 32-bit process running in WOW64, so launch 64-bit.
   if NOT exist "%windir%\SysNative\cmd.exe" (
      call :echoAndLog "You must run this script from a 64-bit machine or install the patch found in KB 942589."
      pause
      exit /b 1
   )
   %windir%\SysNative\cmd.exe /c %0 %*
   exit /b %ERRORLEVEL%
)

if NOT "%ssl_tool_no_admin_check%"=="1" (
   call:checkIfAdmin
   if ERRORLEVEL 1 (
      call :echoAndLog "The current account does not appear to be a member ot the Administrators group."
      call :echoAndLog "Administrative privileges are required to execute the tool. To skip"
      call :echoAndLog "this verification, set the 'ssl_tool_no_admin_check' environment variable to 1."
      pause
      goto :eof
   )
)

if not exist "%ROLLBACK_BACKUP_FOLDER%" mkdir "%ROLLBACK_BACKUP_FOLDER%"
if not exist "%ROLLBACK_BACKUP_FOLDER%" (
   call :echoAndLog "Cannot create rollback folder at %ROLLBACK_BACKUP_FOLDER%"
   goto :eof
)
if not exist "%LOGS_FOLDER%" mkdir "%LOGS_FOLDER%"
if not exist "%LOGS_FOLDER%" (
   call :echoAndLog "Cannot create log folder at %LOGS_FOLDER%."
   goto :eof
)

call:setJavaHome 2>nul
if errorlevel 1 (
   call :echoAndLog "No VMware JRE was found on this system which means that none of tool's supported VMware products is installed on that system."
   goto :eof
)

rem first check if the tool should run one time or once per service
if NOT "%1"=="" (
   rem If anything else is passed (e.g. -help, -v, --version) then display usage information
   goto Usage
)

:Menu
echo.
echo ==================================================================
echo  Main menu
echo.
echo  Enter the action you want to run
echo    1. Plan your steps to update SSL certificates(Update Steps Planner)
echo    2. Update Single Sign-On
echo    3. Update Inventory Service
echo    4. Update vCenter Server
echo    5. Update vCenter Orchestrator(vCO)
echo    6. Update vSphere Web Client and Log Browser
echo    7. Update vSphere Update Manager(VUM)
echo    8. End the update process and exit
echo.
set choice=
set /p choice=" The chosen action is: "

if "[%choice%]" == "[8]" goto End
if "[%choice%]" == "[7]" goto VUM
if "[%choice%]" == "[6]" goto NGC
if "[%choice%]" == "[5]" goto VCO
if "[%choice%]" == "[4]" goto VC
if "[%choice%]" == "[3]" goto IS
if "[%choice%]" == "[2]" goto SSO
if "[%choice%]" == "[1]" goto ExecutionPlanner
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto Menu


:ExecutionPlanner
echo.
echo ==================================================================
echo  1. Plan your steps to update SSL certificates(Update Steps Planner)
echo.
echo  Choose the services you want to update:
echo       1. Single Sign-On
echo       2. Inventory Service
echo       3. vCenter Server
echo       4. vCenter Orchestrator
echo       5. vSphere Web Client
echo       6. Log Browser
echo       7. vSphere Update Manager
echo       8. All services(listed above)
echo       9. Return to the main menu
echo.
echo  Example:
echo    To choose the certificate update of Inventory Service,
echo    vCenter Server and vSphere Web Client you would enter: 2,3,5
echo.
set choice=
set /p choice="You chose (enter comma-separated list of numbers): "
if "[%choice%]" == "[9]" goto Menu
goto planExecution


:SSO
rem Update SSO machine
echo.
echo ==================================================================
echo  2. Update the Single Sign-On SSL Certificate
echo.
echo      1. Update the Single Sign-On SSL Certificate
echo      2. Rollback to the previous Single Sign-On SSL Certificate
echo      3. Return to the main menu to update other services
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[3]" goto Menu
if "[%choice%]" == "[2]" goto RollbackSSO
if "[%choice%]" == "[1]" goto SSLUpdateSSO
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto SSO


:IS
rem Update IS machine
echo.
echo ==================================================================
echo  3. Update the Inventory Service SSL Certificate
echo.
echo      1. Update the Inventory Service Trust to Single Sign-On
echo      2. Update the Inventory Service Trust to vCenter Server
echo      3. Update the Inventory Service SSL Certificate
echo      4. Rollback to the previous Inventory Service SSL Certificate
echo      5. Return to the main menu to update other services
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[5]" goto Menu
if "[%choice%]" == "[4]" goto RollbackIS
if "[%choice%]" == "[3]" goto SSLUpdateIS
if "[%choice%]" == "[2]" goto TrustIS-VC
if "[%choice%]" == "[1]" goto TrustIS-SSO
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto IS


:VC
rem Update VC machine
echo.
echo ==================================================================
echo  4. Update the vCenter Server SSL Certificate
echo.
echo      1. Update the vCenter Server Trust to Single Sign-On
echo      2. Update the vCenter Server SSL Certificate
echo      3. Update the vCenter Server Trust to Inventory Service
echo      4. Rollback to the previous vCenter Server SSL Certificate
echo      5. Return to the main menu to update other services
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[5]" goto Menu
if "[%choice%]" == "[4]" goto RollbackVC
if "[%choice%]" == "[3]" goto TrustVC-IS
if "[%choice%]" == "[2]" goto SSLUpdateVC
if "[%choice%]" == "[1]" goto TrustVC-SSO
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto VC


:VCO
rem Update VCO machine
echo.
echo ==================================================================
echo  5. Update the vCenter Orchestrator(vCO) SSL Certificate
echo.
echo      1. Update the vCenter Orchestrator Trust to Single Sign-On
echo      2. Update the vCenter Orchestrator Trust to vCenter Server
echo      3. Update the vCenter Orchestrator(vCO) SSL Certificate
echo      4. Rollback to the previous vCenter Orchestrator SSL Certificate
echo      5. Return to the main menu to update other services
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[5]" goto Menu
if "[%choice%]" == "[4]" goto RollbackVCO
if "[%choice%]" == "[3]" goto SSLUpdateVCO
if "[%choice%]" == "[2]" goto TrustVCO-VC
if "[%choice%]" == "[1]" goto TrustVCO-SSO
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto VCO


:NGC
rem Update NGC and LogBrowser machine
echo.
echo ==================================================================
echo  6. Update the vSphere Web Client and Log Browser SSL Certificates
echo.
echo      1. Update the Web Client Trust to Single Sign-On
echo      2. Update the Web Client Trust to Inventory Service
echo      3. Update the Web Client Trust to vCenter Server
echo      4. Update the Web Client SSL Certificate
echo      5. Update the Log Browser Trust to Single Sign-On
echo      6. Update the Log Browser SSL Certificate
echo      7. Rollback to the previous Web Client SSL Certificate
echo      8. Rollback to the previous Log Browser SSL Certificate
echo      9. Return to the main menu to update other services
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[9]" goto Menu
if "[%choice%]" == "[8]" goto RollbackLogBrowser
if "[%choice%]" == "[7]" goto RollbackNGC
if "[%choice%]" == "[6]" goto SSLUpdateLogBrowser
if "[%choice%]" == "[5]" goto TrustLogBrowser-SSO
if "[%choice%]" == "[4]" goto SSLUpdateNGC
if "[%choice%]" == "[3]" goto TrustNGC-VC
if "[%choice%]" == "[2]" goto TrustNGC-IS
if "[%choice%]" == "[1]" goto TrustNGC-SSO

echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto NGC


:VUM
rem Update VUM machine
echo.
echo ==================================================================
echo  7. Update the vSphere Update Manager(VUM) SSL Certificate
echo.
echo      1. Update the vSphere Update Manager(VUM) SSL Certificate
echo      2. Update the vSphere Update Manager(VUM) Trust to vCenter Server
echo      3. Rollback to the previous vSphere Update Manager SSL Certificate
echo      4. Return to the main menu to update other services
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[4]" goto Menu
if "[%choice%]" == "[3]" goto RollbackVUM
if "[%choice%]" == "[2]" goto TrustVUM-VC
if "[%choice%]" == "[1]" goto SSLUpdateVUM
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto VUM



rem Update SSL certificate options
:SSLUpdateSSO
call:updateSSO_SSL
goto SSO
:SSLUpdateLogBrowser
call:updateLogBrowser_SSL
goto NGC
:SSLUpdateIS
call:updateIS_SSL
goto IS
:SSLUpdateVC
call:updateVC_SSL
goto VC
:SSLUpdateVCO
call:updateVCO_SSL
goto VCO
:SSLUpdateNGC
call:updateNGC_SSL
goto NGC
:SSLUpdateVUM
call:updateVUM_SSL
goto VUM


rem Update Trust options
:TrustIS-SSO
call:trustIS-SSO
goto IS
:TrustIS-VC
call:trustIS-VC
goto IS
:TrustVC-SSO
call:trustVC-SSO
goto VC
:TrustVC-IS
call:trustVC-IS
goto VC
:TrustVUM-VC
call:trustVUM-VC
goto VUM
:TrustVCO-SSO
call:trustVCO-SSO
goto VCO
:TrustVCO-VC
call:trustVCO-VC
goto VCO
:TrustNGC-SSO
call:trustNGC-SSO
goto NGC
:TrustNGC-IS
call:trustNGC-IS
goto NGC
:TrustNGC-VC
call:trustNGC-VC
goto NGC
:TrustLogBrowser-SSO
call:trustLogBrowser-SSO
goto NGC


rem Rollback SSL certificate
:RollbackSSO
call:rollbackSSO
goto SSO
:RollbackLogBrowser
call:rollbackLogBrowser
goto NGC
:RollbackIS
call:rollbackIS
goto IS
:RollbackVC
call:rollbackVC
goto VC
:RollbackVCO
call:rollbackVCO
goto VCO
:RollbackNGC
call:rollbackNGC
goto NGC
:RollbackVUM
call:rollbackVUM
goto VUM
rem end of Menu



:OneVMMode
rem this is run the tool once
rem 1. update SSO SSL certificate
call:updateSSO_SSL
rem 2.1. update IS trust to SSO
call:trustIS-SSO
rem 2.2. update IS SSL certificate
call:updateIS_SSL
rem 3.1. update VC trust to SSO
call:trustVC-SSO
rem 3.2. update VC SSL certificate
call:updateVC_SSL
rem 3.3. update VC trust to IS
call:trustVC-IS
rem 3.4. update VUM trust to VC
call:trustVUM-VC
rem 4.1. update vCO trust to SSO
call:trustVCO-SSO
rem 4.2. update vCO SSL certificate
call:updateVCO_SSL
rem 4.3. update vCO trust to VC
call:trustVCO-VC
rem 5.1. update NGC trust to SSO
call:trustNGC-SSO
rem 5.2. update NGC SSL certificateificate
call:updateNGC_SSL
rem 6.1 update Log Browser trust to SSO
call:trustLogBrowser-SSO
rem 6.2 update Log Browser SSL certificate
call:updateLogBrowser_SSL
rem 7.1. update VUM SSL certificate
call:updateVUM_SSL
goto End

:Usage
    echo %SCRIPT_NAME% version %SCRIPT_VERSION%
    echo %SCRIPT_COPYRIGHT%
    if /i "[%~1]" == "[-v]" goto :eof
    if /i "[%~1]" == "[--version]" goto :eof
    echo.
    echo Usage: %SCRIPT_NAME%
    echo           This tool updates the SSL certificates of several vSphere services
    echo           and the trust between them. If you run the tool without using the
    echo           ssl-environment.bat file to define the default values, you will be
    echo           prompted at each step for the appropriate information.
    echo.
    echo        %SCRIPT_NAME% -v, --version
    echo           Display %SCRIPT_NAME% version.
    echo.
    echo        %SCRIPT_NAME% -h, -? [--help]
    echo           Display %SCRIPT_NAME% usage.
    echo.
    goto :eof


:End
call "%~dp0tools\read-params" -clear-all
echo ==================================================================
call :echoAndLog "Ending using the tool"
echo ==================================================================
goto :eof



rem ##############################################################################
rem #
rem #                                  FUNCTIONS
rem #
rem ##############################################################################






:generateSSO_CSR


rem ####################
:changeParams

rem take the input from env or interactively
set server_domain=testserver.domain.com
set server_short_name=testserver
set server_ip=10.10.254.108

rem common part for a certs in one machine
set country=Country
set state=State
set localityName=City
set organizationName=Company Name
set commonName=testserver.domain.com

rem this will differ between services
set organizationalUnitName=vCenterSSO
rem Until here are the parameters which are highlighted in red in the tool Beta doc 
rem if you want real data you should change them manually and you will receive real CSR



rem maybe
set ssoOrganizationalUnitName=vCenterSSO
rem ... vc, is, ngc, lb, vum, vco

rem type it manually
set orig_key=rui-orig.key

rem #########################
rem End of section :changeParams



rem write a file
echo [ req ] > testConfig.cfg
echo default_bits = 2048 >> testConfig.cfg
echo default_keyfile = rui.key >> testConfig.cfg
echo distinguished_name = req_distinguished_name >> testConfig.cfg
echo encrypt_key = no >> testConfig.cfg
echo prompt = no >> testConfig.cfg
echo string_mask = nombstr >> testConfig.cfg
echo req_extensions = v3_req >> testConfig.cfg
echo. >> testConfig.cfg
echo [ v3_req ] >> testConfig.cfg
echo basicConstraints = CA:FALSE >> testConfig.cfg
echo keyUsage = digitalSignature, keyEncipherment, dataEncipherment >> testConfig.cfg
echo extendedKeyUsage = serverAuth, clientAuth >> testConfig.cfg
echo subjectAltName = DNS:%server_domain%, DNS:%server_short_name%, IP:%server_ip% >> testConfig.cfg
echo. >> testConfig.cfg
echo [ req_distinguished_name ] >> testConfig.cfg
echo countryName = %country% >> testConfig.cfg
echo stateOrProvinceName = %state% >> testConfig.cfg
echo localityName = %localityName% >> testConfig.cfg
echo 0.organizationName = %organizationName% >> testConfig.cfg
echo organizationalUnitName = %organizationalUnitName% >> testConfig.cfg
echo commonName = %commonName% >> testConfig.cfg



rem generate a csr & keys
rem rui-orig.key is the private key in des, rui.key is the private key in rsa format
openssl req -new -nodes -out rui.csr -keyout rui-orig.key -config testConfig.cfg
openssl rsa -in %orig_key% -out rui.key
rem rui.csr is the desired csr

rem delete the config file or not delete it in order the client to have a look at it? (better put messsage that the config file is there...location...)
echo testConfig.cfg in the current folder is the config with which csr is generated
echo rui.key and rui.csr are the private key and the csr generated







goto :eof














:updateSSO_SSL
call "%~dp0tools\read-params.bat" -sso
call :echoAndLog "Services what will be restarted as part of this operation are: vCenter Single Sign-On (if it is stopped it won't be started)."
rem skip the call to validateCertificateChainFully because the sso-updater does the validation internally anyway
call "%~dp0tools\sso-update-ssl.bat" %*
if errorlevel 1 (
   :ssoFails
   call:unsetVariables sso_master_password
   call:printError "update the Single Sign-On SSL certificate"
   goto :eof
)
call:unsetVariables sso_master_password
call:printSuccessfulOperation "update Single Sign-On SSL certificate"
goto :eof


:updateIS_SSL
call "%~dp0tools\read-params.bat" -is
call:validateCertificateChainFully "%is_cert_chain:"=%" "%is_private_key_new:"=%"
if errorlevel 1 (
   goto isFails
)
call :echoAndLog "Services what will be restarted as part of this operation are: vCenter Inventory Service."
call "%~dp0tools\is-update-ssl.bat" %* >> "%LOGS_FOLDER%\is-update-ssl.log" 2>&1
if errorlevel 1 (
   :isFails
   call:unsetVariables sso_admin_password
   call:printError "update Inventory Service SSL certificate"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update Inventory Service SSL certificate"
goto :eof


:updateVC_SSL
call :echoAndLog "Services what will be restarted as part of this operation are: VMware VirtualCenter Server, VMware VirtualCenter Management Webservices and VMware vSphere Profile-Driven Storage Service."
call "%~dp0tools\read-params.bat" -vc
call:validateCertificateChainFully "%vc_cert_chain:"=%" "%vc_private_key:"=%"
if errorlevel 1 (
   goto vcFails
)
call "%~dp0tools\vc-update-ssl.bat" %* >> "%LOGS_FOLDER%\vc-update-ssl.log"
if errorlevel 1 (
   :vcFails
   call:unsetVariables vc_password vc_db_password
   call:printError "update vCenter Server SSL certificate"
   goto :eof
)
call:unsetVariables vc_password vc_db_password
call:printSuccessfulOperation "update vCenter Server SSL certificate"
goto :eof


:updateVCO_SSL
call "%~dp0tools\read-params.bat" -vco
call:validateCertificateChainFully "%vco_cert_chain:"=%" "%vco_private_key:"=%"
if errorlevel 1 (
   goto vcoFails
)
call :echoAndLog "Services what will be restarted as part of this operation are: vCO Server and vCO Configuration. It might take a few minutes."
call "%~dp0tools\vco-update-ssl.bat" %* >> "%LOGS_FOLDER%\vco-update-ssl.log"
if errorlevel 1 (
   :vcoFails
   call:printError "update vCenter Orchestrator SSL certificate"
   goto :eof
)
call:printSuccessfulOperation "update vCenter Orchestrator SSL certificate"
goto :eof


:updateNGC_SSL
call :echoAndLog "Services what will be restarted as part of this operation are: vSphere Web Client"
call "%~dp0tools\read-params.bat" -ngc
call:validateCertificateChainFully "%ngc_cert_chain:"=%" "%ngc_private_key:"=%"
if errorlevel 1 (
   goto ngcFails
)
call "%~dp0tools\ngc-update-ssl.bat" %* >> "%LOGS_FOLDER%\webclient-update-ssl.log"
if errorlevel 1 (
   :ngcFails
   call:unsetVariables sso_admin_password
   call:printError "update vSphere Web Client SSL certificate"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update vSphere Web Client SSL certificate"
goto :eof


:updateLogBrowser_SSL
call "%~dp0tools\read-params.bat" -logbrowser
call:validateCertificateChainFully "%logbrowser_cert_chain:"=%" "%logbrowser_private_key:"=%"
if errorlevel 1 (
   goto log-browserFails
)
call :echoAndLog "Service what will be restarted as part of this operation is: VMware Log Browser"
call "%~dp0tools\logbrowser-update-ssl.bat" %* >> "%LOGS_FOLDER%\logbrowser-update-ssl.log"
if errorlevel 1 (
   :log-browserFails
   call:unsetVariables sso_admin_password
   call:printError "update the Log Browser SSL certificate"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update Log Browser SSL certificate"
goto :eof


:updateVUM_SSL
call "%~dp0tools\read-params.bat" -vum
rem Disable SAN check while we look for other kinds of errors
setlocal
set ssl_tool_no_cert_san_check=1
call:validateCertificateChainFully "%vum_cert_chain:"=%" "%vum_private_key:"=%"
if errorlevel 1 (
   endlocal
   call:setErrorLevel1
   goto vumFails
)
endlocal
rem Now run check again to see if we should warn about SAN errors. There is
rem no need to run check again for warnings if san check is still disabled.
if NOT "%ssl_tool_no_cert_san_check%"=="1" (
   call:validateCertificateChainFully "%vum_cert_chain:"=%" "%vum_private_key:"=%" > nul 2>&1
   if errorlevel 1 (
     call :echoAndLog "WARNING: Certificate's CN or alternative name does not appear to match this host"
   )
)
call :echoAndLog "Services what will be restarted as part of this operation are: VMware vSphere Update Manager (VMware vSphere Update Manager UFA service will also be stopped)."
call "%~dp0tools\vum-update-ssl.bat" %* >> "%LOGS_FOLDER%\vum-update-ssl.log"
if errorlevel 1 (
   :vumFails
   call:unsetVariables vc_password
   call:printError "update vSphere Update Manager SSL certificate"
   goto :eof
)
call:unsetVariables vc_password
call:printSuccessfulOperation "update VUM SSL certificate"
goto :eof



:trustIS-SSO
call :echoAndLog "Services what will be restarted as part of this operation are: vCenter Inventory Service."
call "%~dp0tools\is-update-trust.bat" %* >> "%LOGS_FOLDER%\is-update-trust-to-sso.log"
if errorlevel 1 (
   call:unsetVariables sso_master_password
   call:printError "update Inventory Service trust to Single Sign-On"
   goto :eof
)
call:printSuccessfulOperation "update Inventory Service trust to Single Sign-On"
goto :eof


:trustIS-VC
call :echoAndLog "Services what will be restarted as part of this operation are: vCenter Inventory Service."
call "%~dp0tools\is-update-trust.bat" %* >> "%LOGS_FOLDER%\is-update-trust-to-vc.log"
if errorlevel 1 (
   call:unsetVariables sso_master_password
   call:printError "update Inventory Service trust to vCenter Server"
   goto :eof
)
call:printSuccessfulOperation "update Inventory Service trust to vCenter Server"
goto :eof


:trustVC-SSO
call "%~dp0tools\read-params.bat" -vc-sso
call:validateCertificateChain "%sso_cert_chain:"=%"
if errorlevel 1 goto vc_ssoFails
call "%~dp0tools\vc-update-trust-to-sso.bat" %* >> "%LOGS_FOLDER%\vc-update-trust-to-sso.log"
if errorlevel 1 (
   :vc_ssoFails
   call:unsetVariables sso_cert_chain
   call:printError "update vCenter Server trust to Single Sign-On"
   goto :eof
)
call:printSuccessfulOperation "update vCenter Server trust to Single Sign-On"
goto :eof


:trustVC-IS
rem no need to validate chain because it is not needed as parameter
call :echoAndLog "Services what will be restarted as part of this operation are: VMware VirtualCenter Server, VMware VirtualCenter Management Webservices and VMware vSphere Profile-Driven Storage Service."
call "%~dp0tools\vc-update-trust-to-is.bat" %* >> "%LOGS_FOLDER%\vc-update-trust-to-is.log"
if errorlevel 1 (
   call:printError "update vCenter Server trust to Inventory Service"
   goto :eof
)
call:printSuccessfulOperation "update vCenter Server trust to Inventory Service"
goto :eof


:trustVUM-VC
call "%~dp0tools\read-params.bat" -vum-trust
rem no need to validate chain because it is not needed as parameter
call :echoAndLog "Services what will be restarted as part of this operation are: VMware vSphere Update Manager (VMware vSphere Update Manager UFA service will also be stopped)."
call "%~dp0tools\vum-update-trust-to-vc.bat" %* >> "%LOGS_FOLDER%\vum-update-trust-to-vc.log"
if errorlevel 1 (
   call:unsetVariables vc_password
   call:printError "update vSphere Update Manager trust to vCenter Server"
   goto :eof
)
call:unsetVariables vc_password
call:printSuccessfulOperation "update vSphere Update Manager trust to vCenter Server"
goto :eof


:trustVCO-SSO
call :echoAndLog "Services what will be restarted as part of this operation are: vCO Server and vCO Configuration. It might take a few minutes."
set VCO_TO_SSO_LOG=%LOGS_FOLDER%\vco-update-trust-to-sso.log
call "%~dp0tools\read-params.bat" -vco-sso
call:validateCertificateChain "%sso_cert_chain:"=%"
if errorlevel 1 goto vco_ssoFails
call "%~dp0tools\vco-update-trust.bat" "%VCO_TO_SSO_LOG%" "Single Sign-On" "%sso_cert_chain%" >> "%VCO_TO_SSO_LOG%"
if errorlevel 1 (
   :vco_ssoFails
   call:unsetVariables sso_cert_chain
   call:printError "update vCenter Orchestrator trust to Single Sign-On"
   goto :eof
)
call:printSuccessfulOperation "update vCenter Orchestrator trust to Single Sign-On"
goto :eof


:trustVCO-VC
call :echoAndLog "Services what will be restarted as part of this operation are: vCO Server and vCO Configuration. It might take a few minutes."
set VCO_TO_VC_LOG=%LOGS_FOLDER%\vco-update-trust-to-vc.log
call "%~dp0tools\read-params.bat" -vco-vc
call:validateCertificateChain "%vc_cert_chain:"=%"
if errorlevel 1 goto vco_vcFails
call "%~dp0tools\vco-update-trust.bat" "%VCO_TO_VC_LOG%" "vCenter Server" "%vc_cert_chain%" >> "%VCO_TO_VC_LOG%"
if errorlevel 1 (
   :vco_vcFails
   call:unsetVariables vc_cert_chain
   call:printError "update vCenter Orchestrator trust to vCenter Server"
   goto :eof
)
call:printSuccessfulOperation "update vCenter Orchestrator trust to vCenter Server"
goto :eof


:trustNGC-SSO
call :echoAndLog "Services what will be restarted as part of this operation are: vSphere Web Client"
call "%~dp0tools\read-params.bat" -ngc-sso
rem no need to validate chain because it is not needed as parameter
call "%~dp0tools\ngc-update-trust.bat" -sso %* >> "%LOGS_FOLDER%\webclient-update-trust-to-sso.log"
if errorlevel 1 (
   call:unsetVariables sso_admin_password
   call:printError "update vSphere Web Client trust to Single Sign-On"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update vSphere Web Client trust to Single Sign-On"
goto :eof


:trustNGC-IS
rem no need to validate chain because it is not needed as parameter
call :echoAndLog "Services what will be restarted as part of this operation are: vSphere Web Client"
call "%~dp0tools\ngc-update-trust-by-restart.bat" "Inventory Service" >> "%LOGS_FOLDER%\webclient-update-trust-to-is.log"
if errorlevel 1 (
   call:unsetVariables sso_admin_password
   call:printError "update vSphere Web Client trust to Inventory Service"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update vSphere Web Client trust to Inventory Service"
goto :eof


:trustNGC-VC
rem no need to validate chain because it is not needed as parameter
call :echoAndLog "Services what will be restarted as part of this operation are: vSphere Web Client"
call "%~dp0tools\ngc-update-trust-by-restart.bat" "vCenter Server" >> "%LOGS_FOLDER%\webclient-update-trust-to-vc.log"
if errorlevel 1 (
   call:unsetVariables sso_admin_password
   call:printError "update vSphere Web Client trust to vCenter Server"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update vSphere Web Client trust to vCenter Server"
goto :eof


:trustLogBrowser-SSO
call :echoAndLog "Service what will be restarted as part of this operation is: VMware Log Browser"
call "%~dp0tools\read-params.bat" -logbrowser-sso
rem no need to validate chain because it is not needed as parameter
call "%~dp0tools\logbrowser-update-trust.bat" %* >> "%LOGS_FOLDER%\logbrowser-update-trust-to-sso.log"
if errorlevel 1 (
   call:unsetVariables sso_admin_password
   call:printError "update Log Browser trust to Single Sign-On"
   goto :eof
)
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update Log Browser trust to Single Sign-On"
goto :eof


:rollbackSSO
call "%~dp0tools\read-params.bat" -sso-rollback
call "%~dp0tools\sso-update-ssl.bat" -rollback
call:unsetVariables sso_master_password
call:checkRollbackStatus "Rollback the Single Sign-On SSL certificate"
goto :eof

:rollbackIS
call "%~dp0tools\read-params.bat" -is-rollback
call :echoAndLog "Services what will be restarted as part of this operation are: vCenter Inventory Service."
call "%~dp0tools\is-update-ssl.bat" -rollback >> "%LOGS_FOLDER%\rollback-is.log"
call:unsetVariables sso_admin_password
call:checkRollbackStatus "Rollback the Inventory Service SSL certificate"
goto :eof

:rollbackVC
call "%~dp0tools\read-params.bat" -vc-rollback
call "%~dp0tools\vc-update-ssl.bat" -rollback >> "%LOGS_FOLDER%\rollback-vc.log"
call:unsetVariables vc_password vc_db_password
call:checkRollbackStatus "Rollback the vCenter Server SSL certificate"
goto :eof

:rollbackVCO
call :echoAndLog "Services what will be restarted as part of this operation are: vCO Server and vCO Configuration. It might take a few minutes."
call "%~dp0tools\vco-update-ssl.bat" -rollback >> "%LOGS_FOLDER%\rollback-vco.log"
call:checkRollbackStatus  "Rollback the vCenter Orchestrator SSL certificate"
goto :eof

:rollbackNGC
call "%~dp0tools\read-params.bat" -ngc-rollback
call "%~dp0tools\ngc-update-ssl.bat" -rollback >> "%LOGS_FOLDER%\rollback-webclient.log"
call:unsetVariables sso_admin_password
call:checkRollbackStatus "Rollback the vSphere Web Client SSL certificate"
goto :eof

:rollbackLogBrowser
call "%~dp0tools\read-params.bat" -logbrowser-rollback
call :echoAndLog "Service what will be restarted as part of this operation is: VMware Log Browser"
call "%~dp0tools\logbrowser-update-ssl.bat" -rollback >> "%LOGS_FOLDER%\rollback-logbrowser.log"
call:unsetVariables sso_admin_password
call:checkRollbackStatus "Rollback the Log Browser SSL certificate"
goto :eof

:rollbackVUM
call "%~dp0tools\read-params.bat" -vum-rollback
call :echoAndLog "Services what will be restarted as part of this operation are: VMware vSphere Update Manager (VMware vSphere Update Manager UFA service will also be stopped)."
call "%~dp0tools\vum-update-ssl.bat" -rollback >> "%LOGS_FOLDER%\rollback-vum.log"
call:unsetVariables vc_password
call:checkRollbackStatus "Rollback vSphere Update Manager SSL certificate"
goto :eof

:checkRollbackStatus
if errorlevel 1 (
   call:printError %~1
   goto :eof
)
if errorlevel 0 (
   call:printSuccessfulOperation %~1
)
goto :eof



:goToExecutionPlannerMsg
call :echoAndLog "Go to the next step in the plan that was received from Update Steps Planner."
goto :eof

:planExecution
rem here we already ensured in the start of the script that Java_home is set
set EXECUTION_PLANNER_JAR=%~dp0tools\execution-planner.jar
set EXECUTION_PLANNER_LOG=%LOGS_FOLDER%\execution-planner.log
"%JAVA_HOME%\bin\java" -Dexecution-planner.log-file="%EXECUTION_PLANNER_LOG%" -jar "%EXECUTION_PLANNER_JAR%" %choice%
if errorlevel 1 call :echoAndLog "The information you provided is incorrect."
goto ExecutionPlanner

:setJavaHome
set JAVA_HOME=
set REG_EXE=%windir%\system32\reg.exe
set _JAVA_HOME_REG_PATH="HKEY_LOCAL_MACHINE\SOFTWARE\VMware, Inc.\VMware Infrastructure\JRE\VIM_JRE"
for /F "tokens=1,2*" %%i in ('%REG_EXE% query %_JAVA_HOME_REG_PATH% /v "InstallPath"') DO (
    if "%%i"=="InstallPath" (
        SET "JAVA_HOME=%%k"
        goto javaHomeSet
    )
)

set _JAVA_VUM_HOME_REG_PATH="HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\VMware, Inc.\VMware Update Manager"
for /F "tokens=1,2*" %%i in ('%REG_EXE% query %_JAVA_VUM_HOME_REG_PATH% /v "InstallPath"') DO (
    if "%%i"=="InstallPath" (
        SET "JAVA_HOME=%%k"
    )
)

set _JAVA_VCO_HOME_REG_PATH="HKEY_LOCAL_MACHINE\SOFTWARE\VMware, Inc.\VMware Infrastructure\Orchestrator"
if "%JAVA_HOME%"=="" (
    for /F "tokens=1,2*" %%i in ('%REG_EXE% query %_JAVA_VCO_HOME_REG_PATH% /v "InstallPath"') DO (
        if "%%i"=="InstallPath" (
            SET "JAVA_HOME=%%k"
        )
    )
)

set _JAVA_VCO_ALT_HOME_REG_PATH="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\vCenter Orchestrator"
if "%JAVA_HOME%"=="" (
    for /F "tokens=1,2*" %%i in ('%REG_EXE% query %_JAVA_VCO_ALT_HOME_REG_PATH% /v "InstallLocation"') DO (
        if "%%i"=="InstallLocation" (
            SET "JAVA_HOME=%%k"
        )
    )
)

if NOT "%JAVA_HOME%"=="" (
    if "%JAVA_HOME:~-1%" == "\" (
        SET "JAVA_HOME=%JAVA_HOME%jre\"
    ) else (
        SET "JAVA_HOME=%JAVA_HOME%\jre\"
    )
    goto javaHomeSet
)

rem here we should exit because we can't find the vmware jre
call :echoAndLog "VMware JRE is not installed on this machine."
pause
exit /B 1

:javaHomeSet
echo [%DATE% - %TIME%]: VMware JRE: %JAVA_HOME% >> "%LOGS_FOLDER%\%SCRIPT_NAME%.log"
exit /B 0
rem end of function setJavaHome

:checkIfAdmin
set WHOAMI_EXE=%windir%\system32\whoami.exe

if NOT exist "%WHOAMI_EXE%" (
   call :echoAndLog "WARNING: could not verify that the user has Administrative privileges."
   exit /B 0
)

set SAW_ADMIN_GROUP=0
for /F "tokens=3,* delims=," %%i in ('"%WHOAMI_EXE%" /groups /fo csv') DO (
   if "%%i"==""S-1-5-32-544"" (
      set SAW_ADMIN_GROUP=1
   )
)
if "%SAW_ADMIN_GROUP%"=="0" (
   call :echoAndLog "ERROR: The current account does not appear to be a member of the Administrators group."
   exit /B 1
)

rem Test for a few example privileges that most admins have
set privCount=0
for /F "tokens=1,*" %%i in ('"%WHOAMI_EXE%" /priv /fo table') DO (
   if "%%i"=="SeTakeOwnershipPrivilege"      set /a privCount=privCount+1
   if "%%i"=="SeLoadDriverPrivilege"         set /a privCount=privCount+1
   if "%%i"=="SeBackupPrivilege"             set /a privCount=privCount+1
   if "%%i"=="SeRestorePrivilege"            set /a privCount=privCount+1
   if "%%i"=="SeImpersonatePrivilege"        set /a privCount=privCount+1
   if "%%i"=="SeCreateGlobalPrivilege"       set /a privCount=privCount+1
)

if %privCount% LSS 6 (
   call :echoAndLog "ERROR: An administrator account is required to perform this task. Only %privCount% of 6 privileges needed were detected."
   exit /B 1
)

exit /B 0
rem end of function checkIfAdmin

rem ##############################################################################
rem #
rem # This function is used to check if the given file contains a certificate
rem # chain which can be loaded and ends in self-signed certificate
rem #
rem # --first argument is the path to certificate chain
rem #
rem ##############################################################################
:validateCertificateChain
echo.
rem here we already ensured in the start of the script that Java_home is set
set VALIDATION_TOOL_JAR=%~dp0tools\sso-updater.jar
set VALIDATION_TOOL_LOG=%LOGS_FOLDER%\validation.log
"%JAVA_HOME%\bin\java" -cp "%VALIDATION_TOOL_JAR%" ^
-Dsso-updater.tool.log-file="%VALIDATION_TOOL_LOG%" com.vmware.sso.cfg.LoadCertificateChain "%~1"
set JAVAERRORLEVEL=%ERRORLEVEL%
rem if error level is 3 then null the environment variables and also don't enter in the team scripts
exit /B %JAVAERRORLEVEL%
rem end of function validateCertificateChain

rem ##############################################################################
rem #
rem # This function is used to check if the given certificate chain is a chain
rem # and chain and the private key are matching.
rem #
rem # --first argument is the path to certificate chain
rem # --second argument is the path to private key
rem #
rem ##############################################################################
:validateCertificateChainFully
echo.
rem here we already ensured in the start of the script that Java_home is set
set VALIDATION_TOOL_JAR=%~dp0tools\sso-updater.jar
set VALIDATION_TOOL_LOG=%LOGS_FOLDER%\validation.log
"%JAVA_HOME%\bin\java" -cp "%VALIDATION_TOOL_JAR%" ^
-Dsso-updater.tool.log-file="%VALIDATION_TOOL_LOG%" com.vmware.sso.cfg.ValidateChainMain "%~1" "%~2"
set JAVAERRORLEVEL=%ERRORLEVEL%
rem if error level is 3 then null the environment variables and also don't enter in the team scripts
exit /B %JAVAERRORLEVEL%
rem end of function validateCertificateChainFully

rem ##############################################################################
rem #
rem # This function is used to echo a message and log it.
rem #
rem ##############################################################################
:echoAndLog
   echo [%DATE% - %TIME%]: %~1
   echo [%DATE% - %TIME%]: %~1 >> "%LOGS_FOLDER%\%SCRIPT_NAME%.log"
exit /B 0
rem end of function echoAndLog

rem ##############################################################################
rem #
rem # This function is used to check if last operation is failed with error code 1
rem # and report detailed message set in "last_error" variable.
rem #
rem # --first argument is the name of the operation
rem #
rem ##############################################################################
:printError
set inputErrorlevel=%errorlevel%
set last_errorNonEmpty=%last_error%""
set last_errorWithoutQuotes=%last_errorNonEmpty:"=%
echo.
call :echoAndLog "Last operation %~1 failed :"
if "%inputErrorlevel%"=="3" (
    call :echoAndLog "The input parameters are missing or incorrect. Check the logs for more details."
) else if "%inputErrorlevel%"=="2" (
    call :echoAndLog "The service is not installed on that machine."
) else if "%inputErrorlevel%"=="1" (
    call :echoAndLog "%last_errorWithoutQuotes%"
) else (
    call :echoAndLog "Unknown reason code %inputErrorlevel%."
)
goto :eof
rem end of function printError

rem ##############################################################################
rem #
rem # This function is used to check if last operation is successful
rem # and unset the variables which are given as parameters
rem #
rem # --first argument is the name of the operation
rem #
rem ##############################################################################
:printSuccessfulOperation
echo.
if errorlevel 1 (
   call :echoAndLog "Last operation %~1 failed."
   goto :eof
)
call :echoAndLog "Last operation %~1 completed successfully."
call:goToExecutionPlannerMsg
goto :eof
rem end of functions printSuccessfulOperation

:unsetVariables
set PRIORERRORLEVEL=%ERRORLEVEL%
rem parameters are names of variables to be unset
FOR %%v IN (%*) DO (
   echo Param to unset: %%v >> "%LOGS_FOLDER%\%SCRIPT_NAME%.log"
   set "%%v="
)
exit /B %PRIORERRORLEVEL%
rem end unsetVariables

rem force errorlevel to 1
:setErrorLevel1
exit /B 1
