local args = { ... }
errMess = 'ERROR'
cancelRequest = false
errorCatch = false
-- This is the program/script that actually re-installs all of the scripts on the computer
termX, termY = term.getSize()
elements = {}

for i=1, 3 do
 url = "https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/version"
 if url == nil then errora.err('Updater URL', 'The Update Source URL Is Empty! Please Report If Not Your Fault') end
  local response = http.get(url)
  if response then
    local data = response.readLine()
  else
	errora.err("The Update URL Cannot Be Resolved Or Is Missing [404]", 'Cant Reach: '..url, true, false)
  end
end

requiredApis = {
	'api/element',
	'api/titleBar',
	'api/LogFile',
	'api/update'
}

scanFiles = {
	'api/element',
	'api/titleBar',
	'api/LogFile',
	'api/update',
	'api/download',
	'api/errora',
	'api/uInput',
	'api/printer',
	'api/systemCheck',
	'startup',
	'version',
	'systemFiles/Programs/dualKey',
	'systemFiles/Programs/reactor',
	'systemFiles/Programs/keycard',
	'systemFiles/Programs/keycardDual',
	'systemFiles/Programs/OpenPDetect',
	'systemFiles/Programs/pin',
	'systemFiles/Programs/rangeLock',
	'systemFiles/Images/BootLogos/boot0.nfp',
	'systemFiles/Images/BootLogos/boot1.nfp',
	'systemFiles/Images/BootLogos/boot2.nfp',
	'systemFiles/Images/BootLogos/boot3.nfp',
	'systemFiles/Images/BootLogos/boot4.nfp',
	'systemFiles/Images/BootLogos/boot5.nfp',
	'systemFiles/Images/BootLogos/boot6.nfp',
	'systemFiles/Images/BootLogos/boot7.nfp',
	'systemFiles/Images/progressBar/load0.nfp',
	'systemFiles/Images/progressBar/load1.nfp',
	'systemFiles/Images/progressBar/load2.nfp',
	'systemFiles/Images/progressBar/load3.nfp',
	'systemFiles/Images/progressBar/load4.nfp',
	'systemFiles/Images/progressBar/load5.nfp',
	'systemFiles/Images/progressBar/load6.nfp',
	'systemFiles/Images/progressBar/load7.nfp',
	'systemFiles/Images/progressBar/load8.nfp',
	'systemFiles/Images/Update/update1.nfp',
	'systemFiles/Images/Update/update2.nfp',
	'systemFiles/Images/Update/update3.nfp',
	'systemFiles/Install/installer',
	'systemFiles/Install/updater',
	'systemFiles/Install/setup',
	'Documentation/LICENSE',
	'Documentation/README'
}

function oldVersion()
	for _, api in ipairs(requiredApis) do
		if not fs.exists(api) then missingFileApi = true end
	end
	if missingFileApi then
		--New Version Release... Un comment below when ready, also comment rest
		printer.centered('Version 2.0.0 Is Now Available...', 6)
		printer.centered('This Version Requires The Suite To Be', 8)
		printer.centered('Re-Installed, Please Wait While We Do This For You!', 9)
		printer.centered('Please Wait While We Update!', 18)
		printer.centered('Downloading New Installer', 19)
		sleep(1)
		download.git('https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Install/installer', 'systemFiles/Install/installer', false, nil)
		printer.centered('We Have Downloaded The Installer', 19)
		shell.run('systemFiles/Install/installer', 'auto')
		term.clear()
		local f = fs.open('systemFiles/Install/updateConfig', 'r')
		updaterSetting = f.readLine()
		f.close()
		printer.centered('Congratulations, Your Are Now Upgraded', 6)
		printer.centered('You Have Just Installed The Next Tier Of Security', 8)
		printer.centered('Please Wait While We Check Some Things', 10)
		printer.centered('Checking Files', 18)
		missingCheckFile = false
		for _, file in ipairs(scanFiles) do
			sleep(0.1)
			printer.centered(file, 19)
			if not fs.exists(file) then
				missingCheckFile = true
			end
			--Delete old configs to stop crashing
			if fs.exists('systemFiles/Programs/dualKeyConfig') then fs.delete('systemFiles/Programs/dualKeyConfig') end
			if fs.exists('systemFiles/Programs/pinConfig') then fs.delete('systemFiles/Programs/pinConfig') end
		end
		
		if not missingCheckFile then
			if updaterSetting == 'quiet' then os.reboot() end
			term.clear()
			printer.centered('Woooo Hooo!', 6)
			printer.centered('You Have Successfully Installed This System', 8)
			printer.centered('Click Anywhere To Reboot, Or Wait For Auto Reboot', 18)
				local function timerReboot()
					for i=10, 1, -1 do
						printer.centered('Auto Reboot In: '..i, 19)
						sleep(1)
						if i == 1 then os.reboot() end
					end
				end
				
				local function click()
					os.pullEvent('mouse_click')
					os.reboot()
				end
				paralell.waitForAny(click, timerReboot)
				os.reboot()
		else
			term.clear()
			printer.centered('Thats Not Good!', 6)
			printer.centered('It Seems Files That Should Have Been Downloaded', 8)
			printer.centered('Are Missing From Your File System,', 9)
			printer.centered('Rest assured, I am Almost Definetely Aware Of This', 11)
			printer.centered('And This Issue Will Be Resolved', 12)
			printer.centered('If Significant Time Has Passed And It Still Isnt Fixed', 13)
			printer.centered('Then Please Report This As A Bug', 14)
			sleep(10)
			os.shutdown()
		end
		os.reboot()
	end
end

function drawTitleBar()
  term.setBackgroundColor(128)
  term.setCursorPos(1,1)
  term.clearLine()
  term.setTextColor(colors.cyan)
  write "HbombOS Security Solutions"
  term.setCursorPos(1,2)
  term.clearLine()
  term.setTextColor(256)
  write "Updater"
  term.setTextColor(1)
  term.setBackgroundColor(256)
end

oldVersion() --Checks the version

function btnInit(btnText, btnWidth, btnHeight, btnX, btnY, btnTC, btnBG, oTC, oBG, onClick, toggle, secBG, secTC, secText) --Function to create button
	local btn = element.create(btnText, btnWidth, btnHeight, btnX, btnY, btnTC, btnBG, oTC, oBG, onClick, toggle, secBG, secTC, secText) --Calls API to generate button
	table.insert(elements, btn) --Inserts into table so it can be scanned later
	element.opacity(btn, true) --Sets visibility to true
	return btn
end


yes = btnInit('Update', nil, nil, termX-(#'Update' + 2), 18, 1, colors.green, 1, 256, function() downloadStart() end, false, nil, nil, nil)
no = btnInit('Dont Update', nil, nil, 2, 18, 1, colors.red, 1, 256, function() os.queueEvent('cancel') request_code = "Cancelled" return 'Cancelled' end, false, nil, nil, nil)
element.opacity(yes, false)
element.opacity(no, false)

function PrintCentered(text, y)
	local w, h = term.getSize()
    x = math.ceil(math.ceil((w / 2) - (#text / 2)), 0)+1
    term.setCursorPos(x, y)
	term.clearLine()
    write(text)
end



function downloadStart()
	term.clear()
	drawTitleBar()
	PrintCentered("Updating...", 4)
	sleep(1)
	PrintCentered("Connection Established", 6)
	sleep(0.1)
	PrintCentered("Starting Download", 6)
	downloadStatus = downloader()
	if downloadStatus == 'Error' then
	  request_code = 'Error'
	  return 'Error'
	end
	PrintCentered("Finished Downloading Scripts", 6)
	local f = fs.open('version', 'r')
	local currentVersion = f.readLine()
	f.close()
	if currentVersion == "2.0.0.2" then
		if fs.exists('systemFiles/Programs/keycardConfig') then
			fs.delete('systemFiles/Programs/keycardConfig')
		end
	end
	sleep(1)
	term.clear()
	drawTitleBar()
	PrintCentered ("Thank You For Updating", 6)
	PrintCentered ("We Hope You Enjoy Your New Security Suite", 8)
	PrintCentered ("Please Report Any Bugs You Find On The Forums", 10)
	PrintCentered ("Press Any Key To Finish", 19)
	os.pullEvent("key")
	term.setBackgroundColor(colors.black)
	term.clear()
	term.setCursorPos(1,1)
	term.clearLine()
	os.reboot()
end

function doClick(event, btn, x, y)
	functionToRun = element.tryClick(elements, x, y)
	if functionToRun then --Check click location
		functionToRun()
	end
end


function welcome()
term.setBackgroundColor(256)
term.clear()
drawTitleBar()
PrintCentered("Welcome to the HbombOS Updater", 4)
PrintCentered("This Updater Will Guide", 6)
PrintCentered("You Through Updating Your Security Suite", 7)
element.opacity(no, true)
element.opacity(yes, true)
while true do
	local event, button, x, y = os.pullEvent()
		if event == "mouse_click" then
			doClick(event, button, x, y)
		elseif event == "cancel" then
			return 'Cancelled'
		end
end
request_code = 'Cancelled'
element.opacity(no, false)
element.opacity(yes, false)
return
end


function downloader(quietDownload, quick)
drawTitleBar()
PrintCentered("Downloading Scripts From GitHub... Please Wait", 6)
PrintCentered("", 19)
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/startup", "startup", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/version", "version", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Install/installer", "systemFiles/Install/installer", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Install/updater", "systemFiles/Install/updater", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Install/setup", "systemFiles/Install/setup", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot0.nfp", "systemFiles/Images/BootLogos/boot0.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot1.nfp", "systemFiles/Images/BootLogos/boot1.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot2.nfp", "systemFiles/Images/BootLogos/boot2.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot3.nfp", "systemFiles/Images/BootLogos/boot3.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot4.nfp", "systemFiles/Images/BootLogos/boot4.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot5.nfp", "systemFiles/Images/BootLogos/boot5.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot6.nfp", "systemFiles/Images/BootLogos/boot6.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/BootLogos/boot7.nfp", "systemFiles/Images/BootLogos/boot7.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/Update/update1.nfp", "systemFiles/Images/Update/update1.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/Update/update2.nfp", "systemFiles/Images/Update/update2.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/Update/update3.nfp", "systemFiles/Images/Update/update3.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load0.nfp", "systemFiles/Images/progressBar/load0.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load1.nfp", "systemFiles/Images/progressBar/load1.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load2.nfp", "systemFiles/Images/progressBar/load2.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load3.nfp", "systemFiles/Images/progressBar/load3.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load4.nfp", "systemFiles/Images/progressBar/load4.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load5.nfp", "systemFiles/Images/progressBar/load5.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load6.nfp", "systemFiles/Images/progressBar/load6.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load7.nfp", "systemFiles/Images/progressBar/load7.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Images/progressBar/load8.nfp", "systemFiles/Images/progressBar/load8.nfp", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/download", "api/download", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/systemCheck", "api/systemCheck", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/update", "api/update", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/printer", "/api/printer", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/titleBar", "/api/titleBar", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/errora", "/api/errora", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/LogFile", "/api/LogFile", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/element", "/api/element", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/api/uInput", "/api/uInput", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/README", "/Documentation/README", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/LICENSE", "/Documentation/LICENSE", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/dualKey", "/systemFiles/Programs/dualKey", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/keycard", "/systemFiles/Programs/keycard", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/keycardDual", "/systemFiles/Programs/keycardDual", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/pin", "/systemFiles/Programs/pin", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/reactor", "/systemFiles/Programs/reactor", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/rangeLock", "/systemFiles/Programs/rangeLock", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/OpenPDetect", "/systemFiles/Programs/OpenPDetect", true, 19) == 'ERROR' then return 'Error' end
if download.git("https://raw.githubusercontent.com/hbomb79/securitySystemPro/master/systemFiles/Programs/remoteControl.lua", "/systemFiles/Programs/remoteControl.lua", true, 19) == 'ERROR' then return 'Error' end
if quietDownload then os.reboot() elseif quick then return else return true end
end

function main()
  if args[1] == 'quiet' then downloader(true) else welcome() end
  if cancelRequest then
	request_code = "Cancelled"
    return 'Cancelled'
  elseif errorCatch then
	request_code = "Error"
    return 'Error'
  end
end


local _, err = pcall(main) --Error Catching, All Functions Are Called From initialise() at some point...
  if err then
    if err == 'Cancelled' then return 'Cancelled' end
	if err == 'Error' then return 'Error' end
    term.setCursorBlink(false)
	errora.err(err, 'Uh Oh, Please Report The Error Code Above', true)
  end