sides = {
"front",
"back",
"left",
"right",
"top",
"bottom"
}

function recieveStartupKey(delay)
	os.startTimer(delay)
	while true do
	  local event, arg = os.pullEvent()
	  if event=='timer' then 
	  	return nil
	  elseif event == "key" or event == "char" then
	  	return arg 
	  end
	  
	end
end

function redstonePulse(side, time)
		redstone.setOutput( side, true )
        sleep(time)
        redstone.setOutput( side, false )
end



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

function verbosePrint(message)
	if verbose then
		print(message)
		sleep(0.1)
	end
end

function displaySystemNoSupport()
	--add a message saying that the display has been moved to monitor
    term.setBackgroundColor(colors.blue)
	term.setTextColor(colors.white)
	term.clear()
	PrintCentered("CPOS Threshold",8)
	PrintCentered("A fatal error has occurred",9)
	PrintCentered("A basic computer was found.",10)
	PrintCentered("Please use CPOS on a Advanced Computer",11)
	PrintCentered("Press any key to boot CraftOS")
	os.pullEventRaw()
	term.clear()
	term.setCursorPos(1,1)
	print(os.version())
end

function displayMovedMessage()
--add a message saying that the display has been moved to monitor
term.setBackgroundColor(colors.lightGray)
term.setTextColor(colors.white)
term.clear()
local line = 7
PrintCentered("To use this screen (not the monitor)",line)
line = line + 1
PrintCentered("------------------------------",line)
line = line + 2
PrintCentered("1. Reboot (Hold Ctrl + R)",line)
line = line + 1
PrintCentered("2. Hold 'M' while the computer starts.",line)
line = line + 1
PrintCentered("OR",line)
line = line + 1
PrintCentered("Open the P Menu and click 'Switch Screen'", line)
end


term.setBackgroundColor(colors.white)
term.setTextColor(colors.black)
term.clear()

--check if the computer is supported
if not term.isColor() then
	displaySystemNoSupport()
	return nil
end

--detect if any boot modifier keys are pressed or the system should has a boot argument
verbose = false
craftos = false
useMonitor = true

os.loadAPI('System/Library/Frameworks/Services/OSTableIO')

local key = nil
if fs.exists("Settings") then
local settings = OSTableIO.load("Settings")
if #settings['boot_arg'] > 0 then
	key = settings['boot_arg']
	settings['boot_arg'] = ""
	OSTableIO.save(settings, "Settings")
else
	key = recieveStartupKey(1)
end
end

if(key == 47) then -- the v key
	verbose = true --boot in verbose mode
elseif(key == 46 or key == "craftos") then -- the c key
	craftos = true --boot in craftos mode
elseif(key == 50) then -- the m key
	useMonitor = false --boot in resume (craftos) mode
end

if craftos then
term.setBackgroundColor(colors.black)
term.setTextColor(colors.yellow)
term.clear()
term.setCursorPos(1,1)
print(os.version() .. " (Opened via CPOS Threshold)")
return nil
end

if verbose then
    term.setCursorPos(1, 1)
	term.setBackgroundColor(colors.black)
	term.setTextColor(colors.white)
	term.clear()
	print("Booting in verbose mode...")
end






usingMonitor = false
if useMonitor then

--find a monitor if there is one and use it
verbosePrint("Searching for monitors...")
for _,side in pairs(sides) do
	if peripheral.isPresent(side) and peripheral.getType(side) == "monitor" then
		verbosePrint("Using monitor on "..side.." side.")
		displayMovedMessage()
		term.redirect(peripheral.wrap(side))
		usingMonitor = true
	else
	end
end

end

if not usingMonitor then
	verbosePrint("No monitors found, using computer screen.")
end

verbosePrint("Searching for peripherals...")
local peripheralsFound = 0
for _,side in pairs(sides) do
	if peripheral.isPresent(side) then
		local type = peripheral.getType(side)
		verbosePrint("Peripheral of type '"..type.."' found on "..side.." side.")
		peripheralsFound = peripheralsFound + 1
	else
	end
end

verbosePrint(peripheralsFound.." peripherals found.")




--draw the 'pear' logo if not verbose mode
verbosePrint("Found 0 monitors, using console.")



verbosePrint("Startup check complete, sending pulse to bottom redstone wire.")

redstonePulse("bottom",0.1)
verbosePrint("To continue with system boot enter 'exit', you can also enter shell commands.")

local wait = verbose

while wait do
	term.write("$ ")
	local command = io.read()
	if command == "exit" then
		print("Starting CPOS Threshold...")
		wait = false
	else
--		commands = split("hello , " ")
		result = shell.run(command)
	end

end



	term.setBackgroundColor(colors.white)
	term.setTextColor(colors.lightGray)
	term.clear()
	logo = paintutils.loadImage("System/Library/Interface/CPOSLogo")
	local logox, logoy = term.getSize()
	paintutils.drawImage(logo,logox/2-3,logoy/2-3)

	shell.run("System/CPOS.lua")


if verbose then
    term.setTextColor(colors.black)
    text = "Starting CPOS Threshold in verbose (debug) mode."
    local screensizex, screensizey = term.getSize()
    PrintCentered(text,screensizey/2+6)
    init()
else
--Crash/Error Handling


local ok, err = pcall(init)

if not ok then
	--an error has occurred, display a warning message
	
	term.setBackgroundColor(colors.blue)
	term.setTextColor(colors.white)
	term.clear()
	PrintCentered("CPOS Threshold",8)
	PrintCentered("A fatal error has occurred",9)
	PrintCentered("Press any key to reboot.",10)
	--PrintCentered("For help hold 'H' while booting.",11)
	PrintCentered("For a more detailed error hold 'V' while booting.",12)

	PrintCentered("The crash error message was:",14)
	term.setTextColor(colours.lightGrey)
	term.setCursorPos(2,16)
	print(err)
	sleep(0.3)
	while true do
		event = os.pullEvent()
		if event == "key" or event == "char" or event == "mouse_click" or event == "monitor_touch" then
			os.reboot()
		end
	end
	
end
 
end