---
-- @package   eg4-crank-ui
-- @file      scan-services.lua
-- @brief     Scans runit services and returns a table of services
--
-- @copyright Copyright 2024 Hanover Displays Limited.
-- @license   This program is the confidential and proprietary product of
--            Hanover Displays Limited. Any unauthorised use, reproduction or
--            transfer of this program is strictly prohibited. (Subject to
--            limited distribution and restricted disclosure only.) All
--            rights reserved.
--

local g4_services = {}

---
--- @brief  Read the list of pids from the trace-debug-pid-list file
--- @return table - the list of pids
local function read_trace_pid_list()
  local pid_list = {}
  local file = io.open("/tmp/trace-debug-pid-list", "r")
  if file then
    -- split the string into a table
    for str in file:read("*all"):gmatch("%S+") do
      table.insert(pid_list, str)
    end
    file:close()
  end
  return pid_list
end

---
--- @brief  Check if the pid is present in the pid file
--- @param  folder - the folder to check
--- @param  pid_list - the list of pids to check
--- @return true if the pid is present
local function check_pid_present(folder, pid_list)
  local file = io.open(folder.."/supervise/pid", "r")
  for line in file:lines() do
    file:close()
    for _, pid in ipairs(pid_list) do
      if pid == line then
        return true
      end
    end
    break
  end
end

---
--- @brief  Scan the run file for the application name
--- @param  folder - the folder to check
--- @return the application name or nil if not found
local function scan_run_for_application_name(folder)
  local application_name
  local file = io.open(folder.."/run", "r")
  if not file then return end
	for line in file:lines() do
    application_name = line:match("^exec /usr/bin/([^ ]+)")
    if application_name then
      break
    end
  end
  file:close()
  return application_name
end

---
--- @brief  Scan the runit services and return a table of services that are present in the pid list
--- @return the table of services
function g4_services:scan()
  local pid_list = read_trace_pid_list()
  local services = {}
  local folders = fileinfo:execute('ls -d1 /var/service/*/ 2>/dev/null')
  for _, folder in ipairs(folders) do
    if check_pid_present(folder, pid_list) then 
      local application_name = scan_run_for_application_name(folder)
      if application_name then
        services[application_name] = services[application_name] or {}
      end
    end
  end
  return services
end

return g4_services
