#!/bin/lua

os.setproc("name", "lua")

if arg[1] == "-e" then
    if arg[2] then
        return load(arg[2])
    else
        print("lua: usage: lua -e [script]")
    end

    os.exit(2)
elseif arg[1] then
    local file = io.open(os.join(arg[1]))
    if file then
        local content = io.read(file, -1)
        if content then
            return load(content)
        end
    else
        print("lua: " .. arg[1] .. ": not found")
        os.exit(127)
    end
end


local previous = graphics.getCurrent()

local term = graphics.new("screen", _VERSION)
local run = graphics.new("command", { label = "Run", type = "ok", priority = 1 })
local back = graphics.new("command", { label = "Back", type = "screen", priority = 1 })
local clear = graphics.new("command", { label = "Clear", type = "screen", priority = 1 })
local switch = graphics.new("command", { label = "Switch to...", type = "screen", priority = 2 })
local output = graphics.new("buffer", {})
local input = graphics.new("field", { type = "field", label = ">" })

local scope = { ["clear"] = function () graphics.SetText(output, "") end }
io.setstdout(output)

graphics.append(term, output)
graphics.append(term, input)
graphics.addCommand(term, run)
graphics.addCommand(term, back)
graphics.addCommand(term, clear)
graphics.addCommand(term, switch)
graphics.handler(term, {
    [run] = function(command)
        if command ~= "" then
            graphics.SetText(input, "")
            local ok, msg = pcall(load, command, scope)
            if not ok then
                print(msg)
            end
        end
    end,
    [back] = function()
        graphics.display(previous)
        os.exit()
    end,
    [clear] = function()
        graphics.SetText(output, "")
    end,
    [switch] = graphics.taskmngr
})

os.setproc("name", "lua")
os.setproc("screen", term)

graphics.display(term)
