#!/usr/bin/env lua


local function copyrec(s, d)
    d = d or {}
    for k,v in pairs(s) do d[k] = v end
    return d
end

local function findandset(line, pattern, ret)
    local t = { line:find(pattern) }
    return t[1] and copyrec({ start = t[1], stop = t[2], select(3, unpack(t)) }, ret)
                 or nil
end

local function regsub_s(t, reg, sub)
  local num
  t.s, num = string.gsub(t.s, reg, sub, 1234567890)
  return num > 0
end

local line,file,modified,pid,running
local pids = {}
local fd = io.popen("sh -c 'vi -r 2>&1'", "r")
while true do
    local t = {}

    line = fd:read("*line")
    if not line then break end
    if findandset(line, "^ *In directory (.*)", t) then
        io.write(t[1].."\n")
    elseif findandset(line, "^ *file name: (.*)", t) then
        file = t[1]
    elseif findandset(line, "^ *modified: (%a*)", t) then
        modified = t[1] ~= "no"
    elseif findandset(line, "^ *process ID: (%d*)(.*)", t) then
        pid = t[1]
	tty = { s = "" }
        if string.find(t[2], "(still running)", 1, true) ~= nil then
	  if pids["pid-"..pid] then
	    tty.s = pids["pid-"..pid]
	  else
	    local ifd = io.popen("ps --no-headers --format tty --pid " .. pid, "r")
	    tty.s = ":" .. ifd:read("*line")
	    ifd:close()
	    if     regsub_s(tty, "tty", "") then
	    elseif regsub_s(tty, "pts/", "pt") then
	    elseif regsub_s(tty, "tts/", "t") then
	    end
	    pids["pid-"..pid] = tty.s
	  end
	end
        if file and modified ~= nil then
            io.write(string.format("%s %5d%-5s %s\n", modified and "+" or "-",
                                   pid, tty.s, file))
        end
        line,file,modified,pid,running = nil
    end
end

