-- Keep the TLCO alive
-- Create a coroutine with alive, and execute the other.

--catch the ground-tasklist

local tasks = {}
for k, v in pairs(startArgs) do
	tasks[k] = v
end
local function drawBlueScreen()
	if flag.STATE_CRASHED then
		term.setCursorPos(1,1)
		term.setBackgroundColor(colors.blue)
		term.setTextColor(colors.white)
		term.clear()
		local msg1 = "Whoops, cLinux crashed!"
		term.setCursorPos(26-#msg1/2, 2)
		term.write(msg1)
		local msg2 = flag.STATE_CRASHED
		local part1 = nil
		local part2 = nil
		if #msg2 > 51 then
			part1 = string.sub(msg2, 1, 51)
			part2 = string.sub(msg2, 52, #msg2)
		end

		if not part1 then
			term.setCursorPos(26-#msg2/2, 4)
			term.setTextColor(colors.red)
			term.write(msg2)
		else
			term.setCursorPos(26-#part1/2, 4)
			term.setTextColor(colors.red)
			term.write(part1)
			term.setCursorPos(26-#part2/2, 5)
			term.setTextColor(colors.red)
			term.write(part2)
		end

		local msg3 = "Please report bugs in GitHub/my post."
		term.setCursorPos(26-#msg3/2, 15)
		term.setTextColor(colors.white)
		term.write(msg3)
		local msg4 = "The computer tries to reboot now..."
		term.setCursorPos(26-#msg4/2, 17)
		term.write(msg4)
	end
end


while true do
	local ok, err = thread.getStatus("Core", tasks)
	if ok == "dead" or flag.STATE_DEAD or ok == nil then
		term.setTextColor(colors.red)
		print("/vit/alive : STATE_DEAD detected. Restarting...")
		term.setCursorBlink(false)
		sleep(2)
		print("Trying to reboot")
		os.reboot()
	elseif flag.STATE_CRASHED then
		drawBlueScreen()
		sleep(4)
		os.reboot()
	elseif flag.STATE_SHUTDOWN then
		term.setTextColor(colors.red)
		print("/vit/alive : Shutting down...")
		term.setCursorBlink(false)
		sleep(2)
		print("Trying shutdown.")
		os.shutdown()
	else
		sleep(0.1)
	end
end