; 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

if(InStr(A_ScriptFullPath, ".ahk"))
Menu, Tray, Icon, %A_scriptdir%\Lib\Update.ico
DetectHiddenWindows, ON



ScriptName = Freedomain Program Updater
ScriptVersion = 1.1
FullScriptName := ScriptName . " "  ScriptVersion


; Notes/Extra Info/#Includes
;------------------------------------------------
#Include, %A_scriptdir%\Lib\SharedFunctions.ahk

; Msgbox % "A_ScriptDir: " A_ScriptDir

; VARIABLES
;------------------------------------------------
SettingsIniFileLocation := A_ScriptDir . "\Settings.ini"
ChangelogIniFilepath := A_ScriptDir . "\Lib\FreedomScriptsChangelogINI"

ScriptBackupFolder := A_ScriptDir . "\Lib\Backups"
FileCreateDir, %ScriptBackupFolder%
; FileCreateDir, %ScriptBackupFolder%


ScriptToUpdate = %1% ; script to update is passed through argument.

; Msgbox % "ScriptToUpdate: " ScriptToUpdate

if(ScriptToUpdate = ""){
	OnMessage(0x44, "OnMsgBoxSelectProgram")
	MsgBox 0x23, %FullScriptName%, Which Program would you like to download an update for?
	OnMessage(0x44, "")

	IfMsgBox Yes, {
		ScriptToUpdate = VideoUploader
		} Else IfMsgBox No, {
			ScriptToUpdate = SocialMediaPoster
			} Else IfMsgBox Cancel, {
				ExitApp
			}
		}

		if(!FileExist(SettingsIniFileLocation)){
			MsgBox 0x30, , Failed to find Settings.ini file. `nExiting
			ExitApp
		}


		ToolTip, Downloading Updates, 850, 0

		; MAIN SCRIPT
		;------------------------------------------------
		
		; Check what the current update
		; msgbox, here goes?
		if(ScriptToUpdate = "VideoUploader"){
			ScriptSettingsSection := "VideoUploader"
		}
		if(ScriptToUpdate = "SocialMediaPoster"){
			ScriptSettingsSection := "SocialMediaPoster"
		}

		; Current Location of the calling script
		IniRead, CallingScriptFilepath, %SettingsIniFileLocation%, %ScriptSettingsSection%, Filepath, %A_space%
		if(CallingScriptFilepath = ""){
			Message = Update Failed`n "CallingScriptFilepath" is blank.`nPlease Submit Error to Yuriy
			MsgBox 0x10,, %Message%
			return
		}
		Iniread, CallingScriptUpdateURL, %ChangelogIniFilepath%, %ScriptSettingsSection%, UpdateURL, %A_space%
		if(CallingScriptFilepath = ""){
			Message = Update Failed`n "ChangelogIniFilepath" is blank.`nPlease Submit Error to Yuriy
			MsgBox 0x10,, %Message%
			return
		}
		Iniread, LastPost, %SettingsIniFileLocation%, %ScriptSettingsSection%, LastPost, %A_space%
		Iniread, ScriptVersion, %SettingsIniFileLocation%, %ScriptSettingsSection%, ScriptVersion, %A_space%
		; Msgbox % "ScriptVersion: " ScriptVersion
		; Msgbox % "CallingScriptFilepath: " CallingScriptFilepath
		; Msgbox % "CallingScriptUpdateURL: " CallingScriptUpdateURL
		; Msgbox % "LastPost: " LastPost


		; Kill the scrip if it is currently open, shouldn't be necessary, but just in case
		SplitPath, CallingScriptFilepath, ProcessName, OutDir, OutExtension, OutNameNoExt, OutDrive
		; SplitPath, InputVar [, OutFileName, OutDir, OutExtension, OutNameNoExt, OutDrive]
		Process, Exist, %ProcessName%
		if(ErrorLevel){
			Process, Close, %ProcessName%
		}

		; Msgbox % "CallingScriptFilepath: " CallingScriptFilepath


		BackupLocation = %ScriptBackupFolder%\%OutNameNoExt%_%ScriptVersion%.%OutExtension%
		FileMove, %CallingScriptFilepath%, %BackupLocation%, 1
		if(ErrorLevel){
			MsgBox 0x10, Failed To Delete, Failed to Delete:`n%ScriptFilepath%`n`nPlease delete it manually and re-run the updater and Select the Program You'd Like to Update.
			ExitApp
		}

		ToolTip, Backup Made to \Backups\ Successfully. `nDownloading New Version, 850, 0
		; Download latest file
		UrlDownloadToFile, %CallingScriptUpdateURL%, %CallingScriptFilepath%

		; IniWrite, Value, Filename, Section, Key
		; Update the ini file with the update status
		IniWrite, 0, %SettingsIniFileLocation%, %ScriptSettingsSection%, UpdateAvailable


		; MsgBox

		run, "%CallingScriptFilepath%" "LastPost"
		; ExitApp
		; MsgBox, done here!


		ExitApp
		; Functions
		;------------------------------------------------
		URLDownloadToVar(url){
			hObject:=ComObjCreate("WinHttp.WinHttpRequest.5.1")
			hObject.Open("GET",url)
			hObject.Send()
			return hObject.ResponseText
		}


		OnMsgBoxSelectProgram() {
			DetectHiddenWindows, On
			Process, Exist
			If (WinExist("ahk_class #32770 ahk_pid " . ErrorLevel)) {
				ControlSetText Button1, Video Uploader
				ControlSetText Button2, Social Media
				ControlSetText Button3, Cancel
			}
		}