@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=5.5
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. Generate Certificate Signing Requests
echo    3. Update Single Sign-On
echo    4. Update Inventory Service
echo    5. Update vCenter Server
echo    6. Update vCenter Orchestrator(vCO)
echo    7. Update vSphere Web Client and Log Browser
echo    8. Update vSphere Update Manager(VUM)
echo    9. End the update process and exit
echo.
set choice=
set /p choice=" The chosen action is: "

if "[%choice%]" == "[9]" goto End
if "[%choice%]" == "[8]" goto VUM
if "[%choice%]" == "[7]" goto NGC
if "[%choice%]" == "[6]" goto VCO
if "[%choice%]" == "[5]" goto VC
if "[%choice%]" == "[4]" goto IS
if "[%choice%]" == "[3]" goto SSO
if "[%choice%]" == "[2]" goto CSR
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


:CSR
rem Generate certificate requests
echo.
echo ==================================================================
echo  2. Generate Certificate Signing Request for:
echo.
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. Other service
echo      9. Return to the main menu
echo.
set choice=
set /p choice=" The chosen service is: "

if "[%choice%]" == "[9]" goto Menu
if "[%choice%]" == "[8]" goto GenerateCSR_Other
if "[%choice%]" == "[7]" goto GenerateCSR_VUM
if "[%choice%]" == "[6]" goto GenerateCSR_LogBrowser
if "[%choice%]" == "[5]" goto GenerateCSR_NGC
if "[%choice%]" == "[4]" goto GenerateCSR_VCO
if "[%choice%]" == "[3]" goto GenerateCSR_VC
if "[%choice%]" == "[2]" goto GenerateCSR_IS
if "[%choice%]" == "[1]" goto GenerateCSR_SSO
echo (input=%choice%) is not a valid choice. Re-enter your choice.
goto CSR


:SSO
rem Update SSO machine
echo.
echo ==================================================================
echo  3. 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  4. 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  5. 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  6. 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  7. 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  8. 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 Generate certificate signing requests
:GenerateCSR_SSO
call:generateCSR sso "generate CSR for Single Sign-On"
goto CSR
:GenerateCSR_IS
call:generateCSR is "generate CSR for Inventory Service"
goto CSR
:GenerateCSR_VC
call:generateCSR vc "generate CSR for vCenter Server"
goto CSR
:GenerateCSR_VCO
call:generateCSR vco "generate CSR for vCenter Orchestrator"
goto CSR
:GenerateCSR_NGC
call:generateCSR ngc "generate CSR for vSphere Web Client"
goto CSR
:GenerateCSR_LogBrowser
call:generateCSR log-browser "generate CSR for Log Browser"
goto CSR
:GenerateCSR_VUM
call:generateCSR vum "generate CSR for vSphere Update Manager"
goto CSR
:GenerateCSR_Other
call:generateCSR other "generate CSR for Other service"
goto CSR


:generateCSR
rem get server info from the system if needed
rem if there is something set in ssl-env- if there is then show this as default
if not defined gen_cert_server_short_name (
	hostname.exe > __hostname.tmp
	set /p gen_cert_server_short_name=<__hostname.tmp
	del __hostname.tmp
)

if not defined gen_cert_server_fqdn (
	rem wmic computersystem get Domain
		for /F "usebackq skip=1 tokens=*" %%i in (`""%windir%\system32\wbem\wmic.exe" computersystem get Domain"`) do (
		set dnssuffix=%%i
		goto setFQDN
	)
	:setFQDN
	rem remove any whitespace in the suffix
	SET gen_cert_server_fqdn=%gen_cert_server_short_name%.%dnssuffix: =%
)

REM rem this is a version where ou is taken directly from the ssl-env
REM if not defined gen_cert_organizational_unit_name (
	REM rem OU for SSO LB
	REM set sso_load_balancer_organizational_unit_name=vCenterSSOLoadBalancer

	REM if /i [%~1] == [sso] set gen_cert_organizational_unit_name_internal=vCenterSSO
	REM if /i [%~1] == [is] set gen_cert_organizational_unit_name_internal=vCenterInventoryService
	REM if /i [%~1] == [vc] set gen_cert_organizational_unit_name_internal=vCenterServer
	REM if /i [%~1] == [vco] set gen_cert_organizational_unit_name_internal=VMwareOrchestrator
	REM if /i [%~1] == [ngc] set gen_cert_organizational_unit_name_internal=vCenterWebClient
	REM if /i [%~1] == [log-browser] set gen_cert_organizational_unit_name_internal=vCenterLogBrowser
	REM if /i [%~1] == [vum] set gen_cert_organizational_unit_name_internal=VMwareUpdateManager
	REM if /i [%~1] == [other] (
		REM set gen_cert_organizational_unit_name_internal=other_service
	REM ) else (
		REM if not defined gen_cert_organizational_unit_name_internal (
			REM echo Generate signing request invoked for %~1 component >> "%LOGS_FOLDER%\generate-csr.log"
			REM goto :csrFails
		REM )
	REM )
	REM set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%gen_cert_server_short_name%
REM ) else (
	REM set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name%
REM )

rem this will suffix OU in ssl-env with service name and host name
set sso_organizational_unit_name=vCenterSSO
set vc_organizational_unit_name=vCenterServer
set is_organizational_unit_name=vCenterInventoryService
set vco_organizational_unit_name=VMwareOrchestrator
set ngc_organizational_unit_name=vCenterWebClient
set log_browser_organizational_unit_name=vCenterLogBrowser
set vum_organizational_unit_name=VMwareUpdateManager
rem OU for SSO LB
set sso_load_balancer_organizational_unit_name=vCenterSSOLoadBalancer
set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name%
if not defined gen_cert_organizational_unit_name (
	if /i [%~1] == [sso] set gen_cert_organizational_unit_name_internal=%sso_organizational_unit_name%
	if /i [%~1] == [is] set gen_cert_organizational_unit_name_internal=%is_organizational_unit_name%
	if /i [%~1] == [vc] set gen_cert_organizational_unit_name_internal=%vc_organizational_unit_name%
	if /i [%~1] == [vco] set gen_cert_organizational_unit_name_internal=%vco_organizational_unit_name%
	if /i [%~1] == [ngc] set gen_cert_organizational_unit_name_internal=%ngc_organizational_unit_name%
	if /i [%~1] == [log-browser] set gen_cert_organizational_unit_name_internal=%log_browser_organizational_unit_name%
	if /i [%~1] == [vum] set gen_cert_organizational_unit_name_internal=%vum_organizational_unit_name%
	if /i [%~1] == [other] (
		set gen_cert_organizational_unit_name_internal=other_service
	) else (
		if not defined gen_cert_organizational_unit_name_internal (
			echo Generate signing request invoked for %~1 component >> "%LOGS_FOLDER%\generate-csr.log"
			goto :csrFails
		)
	)
) else (
	if /i [%~1] == [sso] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%sso_organizational_unit_name%
	if /i [%~1] == [is] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%is_organizational_unit_name%
	if /i [%~1] == [vc] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%vc_organizational_unit_name%
	if /i [%~1] == [vco] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%vco_organizational_unit_name%
	if /i [%~1] == [ngc] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%ngc_organizational_unit_name%
	if /i [%~1] == [log-browser] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%log_browser_organizational_unit_name%
	if /i [%~1] == [vum] set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%vum_organizational_unit_name%
	if /i [%~1] == [other] (
		set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-other_service
	) else (
		if not defined gen_cert_organizational_unit_name_internal (
			echo Generate signing request invoked for %~1 component >> "%LOGS_FOLDER%\generate-csr.log"
			goto :csrFails
		)
	)
)
set gen_cert_organizational_unit_name_internal=%gen_cert_organizational_unit_name_internal%-%gen_cert_server_short_name%

call:read-param-req "Enter the Fully Qualified Domain Name of the server" gen_cert_server_fqdn unquote
if not defined gen_cert_server_ip (
	rem adapterTypeId = 0 means query for all Ethernet 802.3 interfaces and take their indices
	for /F "usebackq skip=1 tokens=1*" %%i in (`""%windir%\system32\wbem\wmic.exe" nic where AdapterTypeId=0 get InterfaceIndex"`) do (
		if /i %%i GTR 0 (
			rem for each index take its nic
			call :queryNIC %%i
		)
	)
	for /f "tokens=* delims= " %%a in ('type all_ips.tmp') do (
		set gen_cert_server_ip=%%a
		goto :setDefaultIP
	)
	:setDefaultIP
	call set gen_cert_server_ip=%%gen_cert_server_ip: =%%

	echo ---IP addresses assigned to this server:
	type all_ips.tmp
	del /q all_ips.tmp
	goto :enterIP_Param

	:queryNIC
	for /F "usebackq skip=1 tokens=1,2,3,4* delims={},; " %%i in (`""%windir%\system32\wbem\wmic.exe" nicconfig where InterfaceIndex=%1 get IPAddress"`) do (
		call :writeToFile %%i
		call :writeToFile %%j
		exit /b 0
	)
	exit /b 0

	:writeToFile
	if NOT "%1"=="" echo %~1 >> all_ips.tmp
	exit /b 0
)
:enterIP_Param
call:read-param-req "Enter the IP Address of the server" gen_cert_server_ip unquote
call:read-param-req "Enter the short hostname of the server" gen_cert_server_short_name unquote
call:read-param-req "Enter the 2 letter code of the country" gen_cert_country unquote
call:read-param-req "Enter the name of the state or province" gen_cert_state unquote
call:read-param-req "Enter the name of the city, locality name" gen_cert_locality_name unquote
call:read-param-req "Enter the name of the organization" gen_cert_organization_name unquote
echo Organizational Unit name will be DN of the certificate and has to be unique!
call:read-param-req "Enter the name of the organizational unit" gen_cert_organizational_unit_name_internal unquote
rem use DNS(FQDN) for CN
set gen_cert_common_name=%gen_cert_server_fqdn%
set component_csr_output_folder="%CSR_OUTPUT_FOLDER%\%gen_cert_organizational_unit_name_internal%"
call:read-param-req "Enter the location where the generated CSR will be saved" component_csr_output_folder unquote
echo.

call:createComponentFolder %component_csr_output_folder% >> "%LOGS_FOLDER%\generate-csr.log" 2>&1
if errorlevel 1 goto :csrFails

call "%~dp0tools\common.bat" Folder to output CSR is : %component_csr_output_folder% >> "%LOGS_FOLDER%\generate-csr.log" 2>&1

REM =================================================================================
call "%~dp0tools\generate-csr.bat" >> "%LOGS_FOLDER%\generate-csr.log" 2>&1
if errorlevel 1 (
   :csrFails
   call :echoAndLog "Last operation %~2 failed. For further details on the error see - %LOGS_FOLDER%\generate-csr.log"
   goto :eof
)
call :echoAndLog "Last operation %~2 completed successfully."
echo.
call :echoAndLog "CSR is located here: %component_csr_output_folder%"
REM =================================================================================
goto :eof



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 ##############################################################################

:updateSSO_SSL
call :echoAndLog "The services that are restarted as a part of this operation are: vCenter Single Sign-On (if it is stopped it won't be started)."
call "%~dp0tools\read-params.bat" -sso
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:unsetVariables sso_admin_password
   call:printError "update the Single Sign-On SSL certificate"
   goto :eof
)
call:unsetVariables sso_master_password
call:unsetVariables sso_admin_password
call:printSuccessfulOperation "update Single Sign-On SSL certificate"
goto :eof


:updateIS_SSL
call :echoAndLog "The services that are restarted as a part of this operation are: vCenter Inventory Service."
call "%~dp0tools\read-params.bat" -is
call:validateCertificateChainFully "%is_cert_chain:"=%" "%is_private_key_new:"=%"
if errorlevel 1 (
   goto isFails
)
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 "The services that are restarted as a 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 :echoAndLog "The services that are restarted as a part of this operation are: vCO Server and vCO Configuration. It might take a few minutes."
call "%~dp0tools\read-params.bat" -vco
call:validateCertificateChainFully "%vco_cert_chain:"=%" "%vco_private_key:"=%"
if errorlevel 1 (
   goto vcoFails
)
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 "The services that are restarted as a 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 :echoAndLog "The services that are restarted as a part of this operation are: VMware Log Browser"
call "%~dp0tools\read-params.bat" -logbrowser
call:validateCertificateChainFully "%logbrowser_cert_chain:"=%" "%logbrowser_private_key:"=%"
if errorlevel 1 (
   goto log-browserFails
)
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 :echoAndLog "The services that are restarted as a part of this operation are: VMware vSphere Update Manager (VMware vSphere Update Manager UFA service will also be stopped)."
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 "%~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 "The services that are restarted as a 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 "The services that are restarted as a 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 "The services that are restarted as a 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 :echoAndLog "The services that are restarted as a part of this operation are: VMware vSphere Update Manager (VMware vSphere Update Manager UFA service will also be stopped)."
call "%~dp0tools\read-params.bat" -vum-trust
rem no need to validate chain because it is not needed as parameter
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 "The services that are restarted as a 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 "The services that are restarted as a 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 "The services that are restarted as a 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 "The services that are restarted as a 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 "The services that are restarted as a 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 "The services that are restarted as a part of this operation are: 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_admin_password
call:checkRollbackStatus "Rollback the Single Sign-On SSL certificate"
goto :eof

:rollbackIS
call :echoAndLog "The services that are restarted as a part of this operation are: vCenter Inventory Service."
call "%~dp0tools\read-params.bat" -is-rollback
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 "The services that are restarted as a 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 :echoAndLog "The services that are restarted as a part of this operation are: VMware Log Browser"
call "%~dp0tools\read-params.bat" -logbrowser-rollback
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 :echoAndLog "The services that are restarted as a part of this operation are: VMware vSphere Update Manager (VMware vSphere Update Manager UFA service will also be stopped)."
call "%~dp0tools\read-params.bat" -vum-rollback
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_NEW_REG_PATH="HKEY_LOCAL_MACHINE\SOFTWARE\VMware, Inc.\VMware Infrastructure\vJRE"
for /F "tokens=1,2*" %%i in ('%REG_EXE% query %_JAVA_HOME_NEW_REG_PATH% /v "InstallPath"') DO (
    if "%%i"=="InstallPath" (
        SET "JAVA_HOME=%%k"
        goto javaHomeSet
    )
)

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 "JRE bundled with VMware services supported by the tool is not installed. This is a prerequesite for running the tool."
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 ##############################################################################
rem #
rem # Like read-param, but forces the user to enter non-empty value.
rem #
rem ##############################################################################
:read-param-req
set input_msg=%~1
set param=%~2
set unquote=%~3

:read-param-req-loop
call:read-param "%input_msg%" "%param%" "%unquote%"
if not defined %param% (
   echo This parameter is required. Enter a non-empty value.
   goto read-param-req-loop
)

exit /b 0
rem end of function // goto:eof

rem ##############################################################################
rem #
rem # This function is used to check if an environment variable is set:
rem #   -- if it is not set then ask the user interactively to set it
rem #   -- if it is set then output its value and ask the user if he wants to set
rem #      it to other value
rem #
rem # --first argument is the message to be displayed to ask the user to enter
rem #   interactively a value for a variable
rem # --second argument is the name of the environment variable
rem # --third argument is the default value of the environment variable
rem #
rem ##############################################################################
:read-param
rem echo all params %*
set input_msg=%~1
set param=%~2
set unquote=%~3
if defined %param% goto definedParam
set /p "%param%=%input_msg%: "

:endReadParam
set temp_var=

if [%unquote%] == [unquote] if defined %param% (
   call set "%param%=%%%param%:"=%%"
)

goto :eof

:definedParam
rem echo Parameter name : %param% is already set to %default_value%
rem the last space is for better view of the parameters in the console
call set "default_value=%%%param%%%"
set input_msg=%input_msg% (default value is: %default_value%): 
set temp_var=
set /p temp_var=%input_msg%
if not defined temp_var (
   rem echo using the default value
   goto :endReadParam
)

set "%param%=%temp_var%"
goto endReadParam
rem end read-param


:createComponentFolder
if not exist "%*" mkdir "%*"
if not exist "%*" (
   call "%~dp0tools\common.bat" Cannot create component CSR output folder at %*. Create it manually and execute the operation once again.
)
goto :eof


rem force errorlevel to 1
:setErrorLevel1
exit /B 1
