#!/usr/bin/env lua

local args = {...}
local tmpfile = os.tmpname()
local cmd = table.concat(args, " ")

-- run the command and write its output to tmpfile
local ok = false
local output = ""

do
  local f = io.popen(cmd, "r")
  if f then
    output = f:read("*a")
    f:close()

    local outFile = io.open(tmpfile, "w")
    if outFile then
      outFile:write(output)
      outFile:close()
    end

    ok = true
  end
end

if ok then
  local session = os.getenv("XDG_SESSION_TYPE")
  if session == "wayland" then
    local f = io.popen("wl-copy", "w")
    if f then
      f:write(output)
      f:close()
    end
  elseif session == "x11" then
    local f = io.popen("xclip -selection clipboard", "w")
    if f then
      f:write(output)
      f:close()
    end
  else
    io.stderr:write("UNKNOWN SESSION TYPE!! >> " .. tostring(session) .. "\n")
    os.remove(tmpfile)
    os.exit(1)
  end

  print(output)
  os.remove(tmpfile)
  os.exit(0)
else
  print(output)
  os.remove(tmpfile)
  os.exit(1)
end
