; ENVIRONMENT
;------------------------------------------------
#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
;#Warn  ; Enable warnings to assist with detecting common errors.
;DetectHiddenWindows, On
#SingleInstance, Force
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
;SetKeyDelay, 500
CoordMode, ToolTip, Screen
CoordMode, Mouse, Screen
;#NoTrayIcon
;Menu, Tray, Icon, ..\Icons\ICONNAMEHERE

; Notes/Extra Info/#Includes
;------------------------------------------------
; https://old.reddit.com/r/PowerShell/comments/nksoh1/keeping_selenium_chromedriver_uptodate/


; VARIABLES
;------------------------------------------------



; MAIN SCRIPT
;------------------------------------------------
#Include C:\Users\%A_UserName%\Documents\Autohotkey\Lib\RunCMD.ahk
#include C:\Users\%A_username%\Documents\Autohotkey\Lib\URLDownloadToVar.ahk



; MAIN SCRIPT
;------------------------------------------------
; MsgBox A_IsAdmin: %A_IsAdmin%`nCommand line: %full_command_line%


; run as admin
full_command_line := DllCall("GetCommandLine", "str")
; Msgbox % "full_command_line: " full_command_line
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
	try
	{
		if A_IsCompiled
		Run *RunAs "%A_ScriptFullPath%" /restart
		else
		Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
	}
	; ExitApp
}


if(!A_IsAdmin){
	MsgBox 0x40040, Information, Failed to get Administrator Authentication which is only needed for copying the chromedriver.exe file into /Program Files/SeleniumBasic. `n`nPress OK to continue and to just download the chromedriver.exe file to the current folder. `n(You will have to move it manually into /Program Files/Selenium Basic)
}


ToolTip, Downloading Chromedriver for your installed chrome version, 850, 0

; ChromeFilepath = C:\Program Files\Chromium\Application\chrome.exe

IniRead, ChromeFilepath, C:\Users\%A_username%\Documents\Autohotkey\Lib\ScriptSettings.ini, Selenium, %A_Computername%, %A_Space%
; Msgbox % "ChromeFilepath: " ChromeFilepath

if(ChromeFilepath = ""){
	if(FileExist("C:\Program Files\Google\Chrome\Application\chrome.exe")){
		ChromeFilepath = C:\Program Files\Google\Chrome\Application\chrome.exe
	}
	else if (FileExist("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")){
		ChromeFilepath = C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
	}
	else, {
		IniRead, ChromeFilepath, C:\Users\%A_username%\Documents\Autohotkey\Lib\ScriptSettings.ini, Selenium, %A_Computername%, "Filepath not found"
		if(!FileExist(ChromeFilepath)){
			msgbox, Chrome.exe not found. Exiting
			ExitApp
		}
	}
}
; Msgbox % "ChromeFilepath: " ChromeFilepath


	/*	IniRead, ChromeFilepath, C:\Users\%A_username%\Documents\Autohotkey\Lib\ScriptSettings.ini, Selenium, %A_Computername%, "Filepath not found"
		if(!FileExist(ChromeFilepath)){
			msgbox, Chrome.exe not found. Exiting
			ExitApp
			}

			*/
			; ChromeFilepath = C:\Users\%A_username%\Downloads\chromedriver.exe

			; VARIABLES
			;------------------------------------------------
			ChromeDriverZipSavePath = C:\Users\%A_username%\Downloads\chromedriver.zip
			ChromeDriverExeExtractParentFolderPath = C:\Users\%A_username%\Downloads\
			ChromeDriverExeExtractedFilepath = %ChromeDriverExeExtractParentFolderPath%chromedriver.exe
			ChromeDriverFinalDestination = C:\Program Files\SeleniumBasic\chromedriver.exe
			; Msgbox % "ChromeFilepath: " ChromeFilepath

			; Check Chrome Version
			; ChromeFilepath = C:\Program Files\Chromium\Application\chrome.exe
			Command = powershell (Get-Item '%ChromeFilepath%').VersionInfo.ProductVersion
			; Command := "powershell (Get-Item 'C:\Program Files\Chromium\Application\chrome.exe').VersionInfo | Select-Object ProductVersion"

			Chromeversion := RunCMD(Command)
			Chromeversion := SubStr(Chromeversion, 1, 2)
			; Msgbox % "Chromeversion: " Chromeversion

			; Chromeversion :=

			if(Chromeversion = ""){
				MsgBox 0x40040, Information, Failed to grab chrome version.`n`nMost Likely reason is that the chrome filepath is incorrect: `nGiven Chrome Filepath:`n%ChromeFilepath%
				ExitApp
			}

			; Msgbox % "Chromeversion: " Chromeversion

			; Query what the latest release chromedriver for the current chrome version is
			URL = https://chromedriver.storage.googleapis.com/LATEST_RELEASE_%Chromeversion%
			URLContents := URLDownloadToVar(URL)

			; Msgbox % "URLContents: " URLContents

			; Chromedriver is always saved in the following format:
			url = https://chromedriver.storage.googleapis.com/%URLContents%/chromedriver_win32.zip

			; Donwload chromedriver
			UrlDownloadToFile, %url%, %ChromeDriverZipSavePath%

			ChromeDriverZipSavePath = '%ChromeDriverZipSavePath%'
			ChromeDriverExeExtractPath = '%ChromeDriverExeExtractPath%'


			; Extract the downloaded zip file using powershell
			Command = powershell Expand-Archive -LiteralPath %ChromeDriverZipSavePath% -DestinationPath %ChromeDriverExeExtractParentFolderPath% -Force
			; Clipboard := Command
			; Msgbox % "Command: " Command
			; Command := "powershell (Get-Item 'C:\Program Files\Chromium\Application\chrome.exe').VersionInfo.ProductVersion"
			; Command := "powershell (Get-Item 'C:\Program Files\Chromium\Application\chrome.exe').VersionInfo | Select-Object ProductVersion"

			PowerShellReturn := RunCMD(Command)
			Msgbox % "PowerShellReturn: " PowerShellReturn

			if(!FileExist(ChromeDriverExeExtractedFilepath)){
				Msgbox, Extracting failed for some reason. `nYou can find the downloaded .zip file in %ChromeDriverZipSavePath%`n`nClick OK to Exit
				ExitApp
			}

			if(!A_IsAdmin){
				Msgbox, Chromedriver was successfully downloaded to:`n %ChromeDriverExeExtractedFilepath%. `n`nPlease copy it over manually to:`n %ChromeDriverFinalDestination%`n`nClick OK to Exit
				ExitApp
			}

			; If run as admin, copy over to Program FIles
			if(A_IsAdmin){
				FileMove, %ChromeDriverExeExtractedFilepath%, %ChromeDriverFinalDestination%, 1
				if(ErrorLevel){
					msgbox, Failed to move chromedriver.exe to /Program Files/SeleniumBasic. `n`nMost Likely reason is that ChromeDriver is currently running in the background because of a recently run script. `nPlease Copy it over manually`n`nClick OK to exit.
					ExitApp
				}
			}

			msgbox, Chromedriver.exe successfully copied to: `n%ChromeDriverFinalDestination% `n`nClick OK to Exit.


			ExitApp






			; Functions
;------------------------------------------------