#!/bin/lua

local xterm = graphics.new("screen", "OpenTTY " .. getAppProperty("MIDlet-Version"))
local run = graphics.new("command", { label = "Run", type = "ok", priority = 1 })
local switchCmd = graphics.new("command", { label = "Switch to...", type = "screen", priority = 2 })

local stdout = graphics.new("buffer", { label = "", value = "", style = "monospace" })
local stdin = graphics.new("field", { label = "Command", value = "", length = 256, mode = "" })

os.setproc("name", "xterm")
os.setproc("stdout", stdout)
os.setproc("screen", xterm)

io.setstdout(stdout)
io.stdin = stdin

local scope, hostname = os.scope(), io.read("/etc/hostname")

io.write(string.env(io.read("/etc/motd")))

local function label() graphics.SetLabel(stdin, "[" .. scope["USER"] .. "@" .. hostname .. " " .. os.getcwd() .. "] " .. (os.getuid() == 0 and "#" or "$")) end

label()

graphics.append(xterm, stdout)
graphics.append(xterm, stdin)
graphics.addCommand(xterm, run)
graphics.addCommand(xterm, switchCmd)
graphics.handler(xterm, {
    [run] = function(command)
        if command ~= "" then
            graphics.SetText(stdin, "")
            local ok, msg = pcall(os.execute, command)
            if not ok then
                print(tostring(msg))
            end
            label()
        end
    end,
    [switchCmd] = graphics.taskmngr
})
graphics.db["xterm"] = xterm
graphics.display(xterm)
