#!/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)
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 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.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
})

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

graphics.display(term)
