@echo off
cls
setLocal EnableDelayedExpansion
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=%APPDATA%\CIRCLE"
rem Set whether we want output info on screen or not
IF NOT "%1"=="" (
    SET "output_on_screen=%1"
) else (
    SET "output_on_screen=False"
)
rem Set whether we want to install selenium or not
IF NOT "%2"=="" (
    SET "install_selenium=%2"
) else (
    SET "install_selenium=False"
)
rem Set which website should the icon point to
SET "website="
IF NOT "%3"=="" (
    IF "%install_selenium%"=="False" (
        SET site=%3
        SET my_site=!site:"=!
        SET "website= -t ^"!my_site!^""
    )
)

:BatchCheckElevated
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set vbs_site=!site:"=""!
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 !output_on_screen! !install_selenium! !vbs_site!", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
    IF NOT "!output_on_screen!"=="False" (
        @echo Elevated rights recived from UAC
    )
:--------------------------------------

rem Start the installation script
IF NOT "!output_on_screen!"=="False" (
    @echo Starting CIRCLE Client install script
    @echo.
)
call :SUB_ARCHITECTURE architecture

rem Decide whether python 2.x is installed or not
SET "python_registry="
:PYTHON_CHECK
SET index=8
:loop
    SET /a index-=1
    IF %index% LSS 6 (
        if "!architecture!"=="64" (
			if "%python_registry%"=="" (
				SET "python_registry=Wow6432Node\"
				GOTO PYTHON_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
    pause
GOTO NOPYTHON

rem No 2.6+ Python is installed
:NOPYTHON
IF NOT "!output_on_screen!"=="False" (
    @echo No 2.6^+ Python is detected on the system.
)
 if "!architecture!"=="64" (
    IF NOT "!output_on_screen!"=="False" (
        @echo 	64 bit system detected, commencing the install
    )
    start /WAIT %running_directory%x64^\python-2.7.7.amd64.msi
    GOTO NOWHASPYTHON
 )
 if "!architecture!"=="32" (
    IF NOT "!output_on_screen!"=="False" (
        @echo 	32 bit system detected, commencing the install
    )
    start /WAIT %running_directory%x86^\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
 IF NOT "!output_on_screen!"=="False" (
     @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 Python installation was successful
 :NOWHASPYTHON
 SET version=2.7
 IF NOT "!output_on_screen!"=="False" (
    @echo Python install finished, rechecking registry
 )
 GOTO UACPrompt
 
 rem We have Python but let's check if it's in the PATH
 :HASPYTHON
    IF NOT "!output_on_screen!"=="False" (
        @echo %version% Python is found, checking PATH variable 
    )
    rem Check Python 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
    )
    rem Check whether python.exe is in the install path (python uninstall doesn't delete registry entrys)
    if NOT EXIST "%install_path%python.exe" (
        IF NOT "!output_on_screen!"=="False" (
            @echo   %version% Python was installed but it is NOT now. Restarting the search for python^^!
        )
        goto loop
    ) else (
        set test=%install_path:~0,-1%
        call %running_directory%inPath test && (IF NOT "!output_on_screen!"=="False" (@echo 	%test% is already in PATH)) || (call %running_directory%addPath test &  setx>nul PATH "%PATH%;%test%" /m & IF NOT "!output_on_screen!"=="False" ( @echo 	%test% set to PATH))
        set test=%install_path%Scripts
        call %running_directory%inPath test && (IF NOT "!output_on_screen!"=="False" (@echo 	%test% is already in PATH)) || (call %running_directory%addPath test &  setx>nul PATH "%PATH%;%test%" /m & IF NOT "!output_on_screen!"=="False" ( @echo 	%test% set to PATH))
    )
 GOTO PIP_CHECK

 
 rem Check whether PIP is installed or not
 :PIP_CHECK
 IF NOT "!output_on_screen!"=="False" (
     @echo.
     @echo Checking if PIP is installed
 )
 IF EXIST %install_path%Scripts/PIP.exe GOTO PIP_VERSION_CHECK
 IF NOT "!output_on_screen!"=="False" (
    @echo 	No PIP found, commencing PIP install
 )
 IF NOT "!output_on_screen!"=="False" (
    call python %running_directory%get-pip.py
 ) else (
    call python %running_directory%get-pip.py >nul 2>&1
 ) 
 rem Try to update the PIP
 :PIP_VERSION_CHECK
 IF NOT "!output_on_screen!"=="False" (
     @echo 	PIP is found
     @echo 		Checking whether the latest PIP is installed
 )
 IF NOT "!output_on_screen!"=="False" (
    call python -m pip install --upgrade pip
 ) else (
    call python -m pip install --upgrade pip >nul 2>&1
 )
 SET "pip_program=requirements.txt"
 IF NOT "!output_on_screen!"=="False" (
    @echo Installing python modules
 )
 GOTO PIP_PACKAGE_INSTALL
 
  rem Check if the PIP package is installed or not
 :PIP_PACKAGE_CHECK
 IF NOT "!output_on_screen!"=="False" (
     @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!" (
        IF NOT "!output_on_screen!"=="False" (
            @echo 	%%b !pip_program! is found
        )
        GOTO CHECK_PACKAGE_LIST
    )
 )
 IF NOT "!output_on_screen!"=="False" (
    @echo No !pip_program! version is found, commencing install
 )
 GOTO PIP_PACKAGE_INSTALL
 
 rem Try to install the PIP packages via PIP
 :PIP_PACKAGE_INSTALL
 if "!pip_program!"=="pywin32" (
    call python %running_directory%pywin_installer.py
 ) else (
    IF NOT "!output_on_screen!"=="False" (
        call python -m pip install -r requirements.txt
    ) else (
        call python -m pip install -r requirements.txt >nul 2>&1
    )
 )
 goto CHECK_PACKAGE_LIST
 
 :CHECK_PACKAGE_LIST
 if "!pip_program!"=="requirements.txt" (
    set "pip_program=pywin32"
    goto PIP_PACKAGE_CHECK
 )
 if NOT "%install_selenium%"=="False" (
    goto CHECK_BROWSER
 ) else (
    goto FIN
 )
 
 rem Get installed browsers
 :CHECK_BROWSER
 set browserToUse=None
 IF NOT "!output_on_screen!"=="False" (
     @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" (
    IF NOT "!output_on_screen!"=="False" (
        @echo 	!count!. %upperBrowser% ^(Recommended^) ^- will be used
    )
    if NOT "%install_selenium%"=="False" (
        SET "browserToUse=firefox"
    )
) else (
    IF NOT "!output_on_screen!"=="False" (
        @echo 	!count!. %upperBrowser%
    )
)
set /a count+=1
GOTO END

rem Determine which Selenium driver to use
:CHECK_BROWSER_TO_USE
if "!browserToUse!"=="None" (
    IF NOT "!output_on_screen!"=="False" (
    @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="
    IF NOT "!output_on_screen!"=="False" (
        @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
                )
                IF NOT "!output_on_screen!"=="False" (
                    @echo Location not found^^! Please add !browserToUse!.exe to PATH manually
                    pause
                )
                goto install_driver
            ) 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 && (IF NOT "!output_on_screen!"=="False" ( @echo 	!myTest! is already in PATH)) || (call %running_directory%addPath myTest & setx>nul PATH "%PATH%;!myTest!" /m & IF NOT "!output_on_screen!"=="False" ( @echo 	!myTest! set to PATH) )
    :install_driver
    IF NOT "%install_selenium%"=="False" (
        if NOT "!selenium_driver_name!"=="" (
            
            @echo Installing the !browserToUse! Selenium driver
            xcopy>nul "%running_directory%%architecture_name%^\%selenium_driver_name%" "!install_location!\" /y
            if ERRORLEVEL 0 (
                IF NOT "!output_on_screen!"=="False" (
                    @echo 	Done
                )
            ) else (
                IF NOT "!output_on_screen!"=="False" (
                    @echo   Error^^! Please copy the ^'chromedriver.exe^' to ^'!install_location!^\^' 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"
            IF NOT "!output_on_screen!"=="False" (
                @echo Installing the Selenium server stand alone JAR
            )
            xcopy>nul "%running_directory%!standalone_version!" "!install_location!\"
            if ERRORLEVEL 0 (
                IF NOT "!output_on_screen!"=="False" (
                    @echo 	Done
                )
                rem And set it in the SELENIUM_SERVER_JAR environment variable
                IF NOT "!output_on_screen!"=="False" (
                    @echo Setting the SELENIUM_SERVER_JAR environment variable
                )
                setx>nul SELENIUM_SERVER_JAR "!install_location!^\!standalone_version!"
                IF NOT "!output_on_screen!"=="False" (
                    @echo 	local SELENIUM_SERVER_JAR set to ^'!install_location!^\!standalone_version!^'
                )
            ) else (
                IF NOT "!output_on_screen!"=="False" (
                    @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
IF NOT "!output_on_screen!"=="False" (
    @echo Checking wheter ^'%install_location%^\^' exists already
)
call %running_directory%inPath install_location && (IF NOT "!output_on_screen!"=="False" ( @echo 	!install_location! is already in PATH)) || (call %running_directory%addPath install_location & setx>nul PATH "%PATH%;!install_location!" /m & IF NOT "!output_on_screen!"=="False" ( @echo 	!install_location! set to PATH))
if not exist "%install_location%\" (
    mkdir "%install_location%"
)
if not exist "%install_location%\.rdp\" (
    mkdir "%install_location%\.rdp"
)
rem Copy the files to the folder
IF NOT "!output_on_screen!"=="False" (
    @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%win_install.py" "%install_location%\" /y
    xcopy>nul "%running_directory%windowsclasses.py" "%install_location%\" /y
    xcopy>nul "%running_directory%nxkey.py" "%install_location%\" /y
    xcopy>nul "%running_directory%OrderedDict.py" "%install_location%\" /y
    xcopy>nul "%running_directory%cloud.ico" "%install_location%\" /y
    xcopy>nul "%running_directory%putty.exe" "%install_location%\" /y
IF NOT "!output_on_screen!"=="False" (
    @echo 	Done
    @echo.
)
IF "%install_selenium%"=="False" (
    SET "create_url_icon= -u" 
) else (
    SET "create_url_icon="
)
IF NOT "!output_on_screen!"=="False" (
    @echo Starting the python installation script
)
if NOT "!browserToUse!"=="" (
    SET "selenium_driver= -d !browserToUse!"
)
IF NOT "!output_on_screen!"=="False" (
    call python %running_directory%win_install.py!selenium_driver! ^-l "%install_location%\\"!create_url_icon!!website!
) else (
    call python %running_directory%win_install.py!selenium_driver! ^-l "%install_location%\\"!create_url_icon!!website! >nul 2>&1
)
IF NOT "!output_on_screen!"=="False" (
    @echo 	Done
    @echo Installation complete
)
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"
)
IF NOT "!output_on_screen!"=="False" (
    @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