@echo off
cls
setLocal EnableDelayedExpansion
@echo Starting CIRCLE Client install script
@echo.
rem Get the running directory for later ease of use
SET running_directory=%~dp0
rem Set where this file will install the rest of the files
SET "install_location=%ProgramFiles%\CIRCLE"
call :SUB_ARCHITECTURE architecture

rem Decide whether python 2.x is installed or not
SET "python_registry="
:PHYTON_CHECK
SET index=-1
:loop
    SET /a index+=1
    IF %index% GTR 7 (
        if "!architecture!"=="64" (
			if "%python_registry%"=="" (
				SET "python_registry=Wow6432Node\"
				GOTO PHYTON_CHECK
			) else (
				GOTO NOPYTHON
			)
        ) else (
			GOTO NOPYTHON
		)
    )
    SET version=2.%index%
    SET @query="hklm\SOFTWARE\%python_registry%Python\PythonCore\%version%"
    reg>nul query %@query% 2>nul
    IF ERRORLEVEL 1 GOTO loop
    IF ERRORLEVEL 0 GOTO HASPYTHON
GOTO NOPYTHON

rem No 2.x Python is installed
:NOPYTHON
@echo No 2.x Python is detected on the system.
 if "!architecture!"=="64" (
    @echo 	64 bit system detected, commencing the install
    start /WAIT %running_directory%python-2.7.7.amd64.msi
    GOTO NOWHASPYTHON
 )
 if "!architecture!"=="32" (
    @echo 	32 bit system detected, commencing the install
    start /WAIT %running_directory%python-2.7.7.msi
    GOTO NOWHASPYTHON
 )
 GOTO ERR
 
 rem Subroutine to decide whether it is 32 or 64 bit
 :SUB_ARCHITECTURE
 rem Decide what architecture the system is using
 if /i %processor_architecture%==AMD64 (
    SET %1=64
    GOTO END
 )
 if /i %PROCESSOR_ARCHITEW6432%==AMD64 (
    SET %1=64
    GOTO END
 )
 if /i %processor_architecture%==x86 (
    SET %1=32
    GOTO END
 )
 GOTO ERR
 
 rem Error within the installation
 :ERR
 @echo Unsupported architecture! Please install files manually
 @echo Please visit: https://www.python.org/downloads/
 @echo Please visit: http://www.mozilla.org/en/firefox/new/
 pause
 GOTO END
 
 rem The install program closed. Check whether the Phyton installation was successful
 :NOWHASPYTHON
 @echo Phyton install finished, rechecking registry
 GOTO PHYTON_CHECK
 
 rem We have Phyton but let's check if it's in the PATH
 :HASPYTHON
    @echo %version% Phyton is found, checking PATH variable 
    rem Check Phyton install path
    set install_path=
    for /f "tokens=2,*" %%a in ('reg query "hklm\SOFTWARE\%python_registry%Python\PythonCore\%version%\InstallPath"') do (
        set install_path=%%b
    )
    set test=%install_path:~0,-1%
    call %running_directory%inPath test && (@echo 	%test% is already in PATH) || (call %running_directory%addPath test &  setx PATH "%PATH%;%test%" /m & @echo 	%test% set to PATH)
    set test=%install_path%Scripts
    call %running_directory%inPath test && (@echo 	%test% is already in PATH) || (call %running_directory%addPath test &  setx PATH "%PATH%;%test%" /m & @echo 	%test% set to PATH)
 GOTO PIP_CHECK

 
 rem Check whether PIP is installed or not
 :PIP_CHECK
 @echo.
 @echo Checking if PIP is installed
 IF EXIST %install_path%Scripts/PIP.exe GOTO PIP_VERSION_CHECK
 @echo 	No PIP found, commencing PIP install
 call phyton %running_directory%get-pip.py
 
 rem Try to update the PIP
 :PIP_VERSION_CHECK
 @echo 	PIP is found
 @echo 		Checking whether the latest PIP is installed
 call python -m pip install --upgrade pip
 SET "pip_program=selenium"
 GOTO PIP_PACKAGE_CHECK
 
 rem Check if the PIP package is installed or not
 :PIP_PACKAGE_CHECK
 @echo.
 @echo Check whether !pip_program! is installed
 for /f "tokens=1,2 delims===" %%a in ('call python -m pip freeze') do (
    if "%%a"=="!pip_program!" (
       @echo 	%%b !pip_program! is found
       GOTO PIP_PACKAGE_UPDATE
    )
 )
 @echo No !pip_program! version is found, commencing install 
 GOTO PIP_PACKAGE_INSTALL
 
 rem Try to install the PIP package via PIP
 :PIP_PACKAGE_INSTALL
 @echo Installing !pip_program!
 call python -m pip install !pip_program!
 goto CHECK_PACKAGE_LIST
 
 rem Try to update Selenium
 :PIP_PACKAGE_UPDATE
 @echo Trying to update !pip_program!
 call python -m pip install --upgrade !pip_program!
 goto CHECK_PACKAGE_LIST
 
 :CHECK_PACKAGE_LIST
 if "!pip_program!"=="selenium" (
    set "pip_program=winshell"
    goto PIP_PACKAGE_CHECK
 )
 goto CHECK_BROWSER
 
 
 rem Get installed browsers
 :CHECK_BROWSER
 set browserToUse=None
 @echo.
 @echo Checking installed browsers 
 rem For 64 bit systems
 START /W REGEDIT /E "%Temp%\BROW3.reg" HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Clients\StartMenuInternet
 rem For 32 bit systems
 if not exist "%Temp%\BROW3.reg" START /W REGEDIT /E "%Temp%\BROW3.reg" HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet
 set count=1
 for /f "tokens=*" %%B in ('type "%Temp%\BROW3.reg" ^| findstr /E "DefaultIcon]"') do (
    rem Extracting browser name from icon path
    set "browser=%%B"
    rem Removing \DefaultIcon] string
    set "browser=!browser:\DefaultIcon]=!"
    rem Get the browser name
    for %%P in ("!browser!") do (
        call :SUB_PRINTBROWSER %%~nP
    )
 )
GOTO CHECK_BROWSER_TO_USE

rem Subroutine to print installed browsers
:SUB_PRINTBROWSER
set subBrowser=%*
CALL :UCase subBrowser upperBrowser
if "%upperBrowser%"=="FIREFOX" (
    @echo 	!count!. %upperBrowser% ^(Recommended^) ^- will be used
    set "browserToUse=firefox"
) else (
    @echo 	!count!. %upperBrowser%
)
set /a count+=1
GOTO END

rem Determine which Selenium driver to use
:CHECK_BROWSER_TO_USE
if "!browserToUse!"=="None" (
    @echo Decide whitch browser to use
        @echo 	Checking which one is the Default browser
        START /W REGEDIT /E "%Temp%\BROW5.reg" HKEY_CLASSES_ROOT\http\shell\open\command
        for /f tokens^=3^ delims^=^" %%B in ('type "%Temp%\BROW5.reg" ^| find "@"') do (
            set "default=%%B"
            rem removing double slashes
            set "default=!default:\\=\!"
            rem removing end slash
            set "default=!default:~0,-1!"
            rem get the name
            for %%D in ("!default!") do (
                call :SUB_DEFAULTBROWSER %%~nD
            )
        )
        del /Q /F "%Temp%\BROW5.reg"
    )
) else (
    rem Registry location depends of the architecture
    if "!architecture!"=="64" (
        set "browser_architect=Wow6432Node\"
        set "architecture_name=x64"
    ) else (
        if "!architecture!"=="32" (
            set "browser_architect="
            set "architecture_name=x86"
        ) else (
            GOTO ERR
        )
    )
    rem Registry names for the different browsers out there
    if "!browserToUse!"=="firefox" (
        set "browser_path_name=FIREFOX.EXE"
        set "selenium_driver_name="
    )
    if "!browserToUse!"=="chrome" (
        set "browser_path_name=Google Chrome"
        set "selenium_driver_name=chromedriver.exe"
    )
    if "!browserToUse!"=="iexplore" (
        set "browser_path_name=IEXPLORE.EXE"
        set "selenium_driver_name=IEDriverServer.exe"
    )
    rem Opera have to versions (in the registry) Opera and OperaStable, we try to Stable first
    if "!browserToUse!"=="opera" (
        set "browser_path_name=OperaStable"
        set "selenium_driver_name="
    )
    set "browser_path="
    @echo Check if !browserToUse!.exe is in PATH
    :get_browser_path
    set browser_path=
    set query="hklm\SOFTWARE\%browser_architect%Clients\StartMenuInternet\%browser_path_name%\shell\open\command"
    reg>nul query %query% 2>nul
    if ERRORLEVEL 1 (
        if "%browser_path%"=="" (
            if "%browser_architect%"=="" (
                rem If the Stable failed check out the simple Opera
                if "%browser_path_name%"=="OperaStable" (
                    SET "browser_path_name=Opera"
                    SET "browser_architect=Wow6432Node\"
                    goto get_browser_path
                )
                @echo Location not found^^! Please add !browserToUse!.exe to PATH manually
                pause
            ) else (
                set "browser_architect="
                goto get_browser_path
            )
        )
    )
    rem Get the installation path for the selected browser
    for /f "tokens=2,*" %%a in ('reg query %query%') do (
        set browser_path=%%b
    )
    set browser_path=%browser_path:"=% 
    call :Split "%browser_path%" test
    set myTest=!test:~0,-1!
    rem Set that path in the PATH environment variable
    call %running_directory%inPath myTest && (@echo 	!myTest! is already in PATH) || (call %running_directory%addPath myTest & setx PATH "%PATH%;!myTest!" /m & @echo 	!myTest! set to PATH)
    if NOT "!selenium_driver_name!"=="" (
        @echo Installing the !browserToUse! Selenium driver
        xcopy>nul "%running_directory%%architecture_name%^\%selenium_driver_name%" "!test!" /y
        if ERRORLEVEL 0 (
            @echo 	Done
        ) else (
            @echo   Error^^! Please copy the ^'chromedriver.exe^' to ^'!test!^' manually
        )
    )
    rem For the Opera we need to install the selenium standalone jar
    if "!browserToUse!"=="opera" (
        SET "standalone_version=selenium-server-standalone-2.42.2.jar"
        @echo Installing the Selenium server stand alone JAR
        xcopy>nul "%running_directory%!standalone_version!" "!test!"
        if ERRORLEVEL 0 (
            @echo 	Done
            rem And set it in the SELENIUM_SERVER_JAR environment variable
            @echo Setting the SELENIUM_SERVER_JAR environment variable
            setx SELENIUM_SERVER_JAR "!myTest!^\!standalone_version!" /m
            @echo 	SELENIUM_SERVER_JAR set to ^'!myTest!^\!standalone_version!^'
        ) else (
            @echo   Error^^! Please copy the ^'%standalone_version%^' to ^'!test!^' manually
        )
    )
    GOTO FIN
)
GOTO ERR

rem Finish up the install
:FIN
rem Create folder if needed and set it to PATH
@echo Checking wheter ^'%install_location%^\^' exists already
call %running_directory%inPath install_location && (@echo 	!install_location! is already in PATH) || (call %running_directory%addPath install_location & setx PATH "%PATH%;!install_location!" /m & @echo 	!install_location! set to PATH)
if not exist "%install_location%\" (
    mkdir "%install_location%"
)
rem Copy the files to the folder
@echo Copying files to ^'%install_location%^'
    xcopy>nul "%running_directory%cloud.py" "%install_location%\" /y
    xcopy>nul "%running_directory%cloud_connect_from_windows.py" "%install_location%\" /y
    xcopy>nul "%running_directory%cloud.ico" "%install_location%\" /y
@echo 	Done
@echo.
@echo Starting the phyton installation script
call python %running_directory%win_install.py ^-d !browserToUse! ^-l "%install_location%\\"
@echo 	Done
@echo Installation complete
@echo Press any key to close this installer
pause
GOTO END

rem Subroutine to decide which Selenium driver to use
:SUB_DEFAULTBROWSER
set defBrowser=%*
CALL :LCase defBrowser lowerFound
if "%lowerFound%"=="launcher" (
    set "lowerFound=opera"
)
@echo 		 %lowerFound% is the default browser
set browserToUse=%lowerFound%
GOTO END


:LCase
:UCase
:: Converts to upper/lower case variable contents
:: Syntax: CALL :UCase _VAR1 _VAR2
:: Syntax: CALL :LCase _VAR1 _VAR2
:: _VAR1 = Variable NAME whose VALUE is to be converted to upper/lower case
:: _VAR2 = NAME of variable to hold the converted value
:: Note: Use variable NAMES in the CALL, not values (pass "by reference")

SET _UCase=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
SET _LCase=a b c d e f g h i j k l m n o p q r s t u v w x y z
SET _Lib_UCase_Tmp=!%1!
IF /I "%0"==":UCase" SET _Abet=%_UCase%
IF /I "%0"==":LCase" SET _Abet=%_LCase%
FOR %%Z IN (%_Abet%) DO SET _Lib_UCase_Tmp=!_Lib_UCase_Tmp:%%Z=%%Z!
SET %2=%_Lib_UCase_Tmp%
GOTO END

rem Subroutine to get the exact path out from a file location, but strip the file name
:Split
SET %2=%~dp1
GOTO END

:END