-- =======================================================
-- LoraCore ModuOS Installer v4.0 (Corrected & Asynchronous)
-- =======================================================
-- Этот скрипт использует coroutine.yield для ожидания завершения
-- файловых операций и возвращает 'true' при успехе или 'false' при ошибке.

local term = tablet.terminal
local gpu = tablet.gpu
local fs = _G.fs
local colors = _G.colors
local coroutine = _G.coroutine

-- Очищаем экран и устанавливаем начальные цвета
term.clear()
gpu.setBackgroundColor(colors.black)
gpu.setTextColor(colors.white)
term.setCursorPos(1, 1)

term.write("Starting ModuOS Installation...\n")
term.write("-------------------------------\n\n")

-- Содержимое операционной системы, которое будет записано в /boot.lua
local boot_script_content = [[
-- /boot.lua - Minimal Operating System v1.1
term.clear()
term.setCursorPos(1, 1)
print("ModuOS v0.1 Loaded.")
print("Type 'help' for commands.")
while true do
    term.write("> ")
    local cmd = term.read()
    if cmd == "help" then
        print("Commands: help, reboot, exit")
    elseif cmd == "reboot" then
        os.reboot()
    elseif cmd == "exit" then
        term.clear()
        print("System halted.")
        break
    else
        print("Unknown command.")
    end
end
]]

-- ШАГ 1: Запись файла ОС
term.write("1. Writing boot file...")
-- ИСПОЛЬЗУЕМ YIELD: Ждем, пока сервер подтвердит запись файла
local ok, err = coroutine.yield(fs.write("/boot.lua", boot_script_content))
if not ok then
    gpu.setTextColor(colors.red)
    term.write("\n   ERROR: Failed to write boot file: " .. tostring(err) .. "\n")
    return false -- Возвращаем неудачу
end
term.write(" [OK]\n")


-- ШАГ 2: Создание директорий
term.write("2. Creating directories...")
-- ИСПОЛЬЗУЕМ YIELD: Ждем создания каждой директории
coroutine.yield(fs.makeDir("/usr"))
coroutine.yield(fs.makeDir("/home"))
term.write(" [OK]\n")


-- ШАГ 3: Проверка установки
term.write("3. Verifying installation...")
-- ИСПОЛЬЗУЕМ YIELD: Ждем, пока сервер прочитает файл и вернет его содержимое
local content = coroutine.yield(fs.read("/boot.lua"))
if not content then
    gpu.setTextColor(colors.red)
    term.write("\n   ERROR: Verification failed! Could not read boot file back.\n")
    return false -- Возвращаем неудачу
end
term.write(" [OK]\n")

-- Если все шаги прошли успешно, возвращаем true.
return true