#!/usr/bin/env lua

local function rofi(prompt, lines)
  local cmd = string.format(
    'printf "%s" | rofi -dmenu -i -p "%s"',
    table.concat(lines, "\n"),
    prompt
  )
  local handle = io.popen(cmd)
  local selection = handle:read("*a")
  handle:close()
  selection = selection:gsub("%s+$", "")
  if selection == "" then return nil end
  return selection
end

local function contains(tbl, val)
  for _, v in pairs(tbl) do
    if v == val then
      return true
    end
  end
  return false
end

-- TODO: Deduplicate This
local options = {
  "Log Out",
  "Shutdown",
  "Restart"
}

local option_pair = {
  ["Log Out"] = "swaymsg exit",
  ["Shutdown"] = "systemctl poweroff",
  ["Restart"] = "systemctl reboot"
}

local choice = rofi("Action:", options)
if (not choice) or (not contains(options,choice)) then os.exit() end

if choice == "Log Out" then
  io.popen(option_pair[choice])
else
  local confirm = rofi("Are you sure?:", {"Yes", "No"})
  if confirm == "Yes" then
    io.popen(option_pair[choice])
  end
end
