--[[
  @package   eg4-crank-ui-2
  @file      file-utilities.lua
  @brief     Various file/folder utilities
]]

fileinfo = {}

---
--- @brief  Check if file or directory exists at this path
--- @param  path  The path to check
--- @return true if the file or directory exists
function fileinfo:exists(path)
  return fileinfo:isfile(path) or fileinfo:isfolder(path)
end

---
--- @brief  Check if a folder exists in this path
--- @param  path  The path to check
--- @return true if the folder exists
function fileinfo:isfolder(path)
  if type(path) ~= "string" then return false end
  return #fileinfo:find_folder(path) ~= 0
end

---
--- @brief  Check if a file exists in this path
--- @param  path  The path to check
--- @return true if the file exists
function fileinfo:isfile(path)
  if type(path) ~= "string" then return false end
  local f = io.open(path, "r")
  if not f then return false end
  f:close()
  return true
end

---
--- @brief  Executes a system command and returns the console output
--- @param  command  The command to execute
--- @return The output of the command as a table of lines
function fileinfo:execute(command)
  local pfile = io.popen(command)
  local lines = {}
  for line in pfile:lines() do
    table.insert(lines, line)
  end
  pfile:close()
  return lines
end

---
--- @brief  Fetches list of files and folders in a dir.
--- @param  path  The path to scan
--- @return The list of files and folders
function fileinfo:scandir(path)
  return fileinfo:execute('ls -1 "'..path..'" 2>/dev/null')
end

---
--- @brief  Finds folders in a specified path
--- @param  path  The path to scan
--- @return The folders
function fileinfo:find_folder(path)
  local t = fileinfo:execute('ls -d -1 '..path..' 2>/dev/null | head -1')
  return t
end

---
--- @brief  Check if any USB storage device is mounted
--- @return true if a USB storage device is mounted
function fileinfo:usb_mounted()
  local file = io.open("/proc/mounts", "r")
  if not file then return false end
  for line in file:lines() do
    local fields = line:split(" ")
    if #fields >= 2 and fields[2]:find("/media/") then
      return true
    end
  end
  return false
end
