local component = require("component")
local computer = require("computer")
local unicode = require("unicode")
local tty = require("tty")

local f = io.open("/usr/misc/greetings.txt")
local lines = {_OSVERSION .. " (" .. math.floor(computer.totalMemory() / 1024) .. "k RAM)"}
local greeting = ""
if f then
  local greetings = {}
  pcall(function()
    for line in f:lines() do table.insert(greetings, line) end
  end)
  f:close()
  greeting = greetings[math.random(1, math.max(#greetings, 1))] or ""
end
local width = math.min(#greeting, (tty.getViewport() or math.huge) - 5)
local maxLine = #lines[1]
while #greeting > 0 do
  local si, ei = greeting:sub(1, width):find("%s%S*$")
  local line = #greeting <= width and greeting or greeting:sub(1, si or width)
  lines[#lines + 1] = line
  maxLine = math.max(maxLine, #line)
  greeting = greeting:sub(#line + 1)
end

local borders = {{unicode.char(0x2552), unicode.char(0x2550), unicode.char(0x2555)},
                 {unicode.char(0x2502), nil, unicode.char(0x2502)},
                 {unicode.char(0x2514), unicode.char(0x2500), unicode.char(0x2518)}}
io.write(borders[1][1], string.rep(borders[1][2], maxLine + 2), borders[1][3], "\n")
for _,line in ipairs(lines) do
  io.write(borders[2][1], " ", line, (" "):rep(maxLine - #line + 1), borders[2][3], " \n")
end
io.write(borders[3][1] .. string.rep(borders[3][2], maxLine + 2) .. borders[3][3] .. "\n")
