--------------------------------------------------------------------------------
-- $Author: fpina $
-- $Revision: 163065 $  - $Date: 2015-03-27 15:41:34 -0300 (Fri, 27 Mar 2015) $
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
--
-- Implementação da interface IDL SGADaemon.
--
--------------------------------------------------------------------------------

local verbose = require "sga.verbose"
local ext = require "shellExtension"

local sgaidl = require "sga.idl"

--------------------------------------------------------------------------------
-- Funções da interface SGADaemon
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------
function SGA_DAEMON:ping()
end -- function SGA_DAEMON:ping

--------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------
function SGA_DAEMON:control(action)
  verbose:kill("Recebida uma requisição de término de SGA!!!")
  local status = 1 -- RESTART
  if (action == "SHUTDOWN") then
    status = 2
  end

  self:exit(status)
end -- function SGA_DAEMON:control

--------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------
--[[ XXX - Rever como usar as constantes no oil
  const string COMMAND_EXECUTION_PATH = "csbase_command_path";
  const string COMMAND_EXECUTION_OUTPUT_PATH = "csbase_command_output_path";
  const string COMMAND_EXECUTION_SANDBOX_PATHS_SEQ = "csbase_command_sandbox_paths";
--]]
function SGA_DAEMON:executeCommand(comm_string, comm_id, extraParamsDictionary)
  local missingParams = {}
  if comm_string == nil or comm_string == "" then
    table.insert(missingParams, "command")
  elseif comm_id == nil or comm_id == "" then
    table.insert(missingParams, "cmdid")
  end

  if #missingParams > 0 then
    sgaidl.throw.MissingParameterException{ parameters = missingParams }
  end

  local extraParams = {}
  if (extraParamsDictionary ~= nil) then
    extraParams = ext.dictionaryToMap(extraParamsDictionary)
  end
  local path = extraParams[CONST.COMMAND_EXECUTION_PATH]
  extraParams[CONST.COMMAND_EXECUTION_PATH] = nil
  local output_path = extraParams[CONST.COMMAND_EXECUTION_OUTPUT_PATH]
  extraParams[CONST.COMMAND_EXECUTION_OUTPUT_PATH] = nil
  local sandbox_paths = {}
  local i = 1
  while (extraParams[CONST.COMMAND_EXECUTION_SANDBOX_PATHS_SEQ.."."..i]) do
    sandbox_paths[i] = extraParams[CONST.COMMAND_EXECUTION_SANDBOX_PATHS_SEQ.."."..i]
    extraParams[CONST.COMMAND_EXECUTION_SANDBOX_PATHS_SEQ.."."..i] = nil
    i = i + 1
  end

  local comm = Command
    {
    command = comm_string,
    id = comm_id,
    path = path,
    output_path = output_path,
    host = nil,
    sandbox_paths = sandbox_paths,
    extraParams = extraParams,
    }
  if comm then
    COMMAND:addCommandToList(comm)
  end

  return comm
end -- function SGA_DAEMON:executeCommand


--------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------
function SGA_DAEMON:getPaths(basePath)
  local basePathInfo = SGA_DAEMON:getPath(basePath)
  if basePathInfo.isSymbolicLink and basePathInfo.isDir then
    if not string.match(basePath, ext.fileSeparator, #basePath) then
      basePath = basePath .. ext.fileSeparator
    end
  end
  local lines, err = ext.ls(basePath, "-ago")
  if err then
    verbose:error(string.format("ERRO: %s", err))
    return {}
  end

  local initPath, err = ext.findInitPath(lines)
  if err then
    verbose:error(string.format("Erro: %s (path: %s)", err, basePath))
    return {}
  end

  local result = {}
  for _, line in ipairs(lines) do
    local fileName = string.sub(line, initPath)
    local isValid = fileName ~= ''
      and fileName ~= '.'
      and fileName ~= './'
      and fileName ~= '..'
      and fileName ~= '../'
    if isValid then
      local absolutePath = ext.buildAbsolutePath(basePath, fileName)
      local pathInfo = SGA_DAEMON:getPath(absolutePath)
      result[#result + 1] = pathInfo
    end
  end
  return result
end -- function SGA_DAEMON:getPaths

--------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------
function SGA_DAEMON:getPath(path)
  local noInfo = {}
  noInfo.isDir = false
  noInfo.isSymbolicLink = false
  noInfo.linkPath = ''
  noInfo.readable = false
  noInfo.writable = false
  noInfo.executable = false
  noInfo.sizeKB = -1
  noInfo.path = path
  noInfo.exists = false

  local attrs = ext.getAttributes(path)
  local exists = attrs.d or attrs.f

  if not exists then
    verbose:error(string.format("ERRO: Path não existe: %s", path))
    -- return noInfo
    sgaidl.throw.PathNotFoundException()
  end

  --converte bytes em KB
  local sizeKB = ext.size(path)/1024

  local pathInfo = {}
  pathInfo.isDir = attrs.d
  pathInfo.isSymbolicLink = attrs.h
  pathInfo.readable = attrs.r
  pathInfo.writable = attrs.w
  pathInfo.executable = attrs.x
  pathInfo.sizeKB = sizeKB
  pathInfo.path = path
  pathInfo.exists = true
  pathInfo.linkPath = ''

  return pathInfo
end -- function SGA_DAEMON:getPath
