local lfs = require("lfs")

local modpath = "/etc/haproxy/mods"

local compile = {}
local lua_version = "5.4"
local user = "haproxy"
local group = "haproxy"
local libs = {"-ljansson", "-lmaxminddb", "-lcurl"}

function compile.check(module)
  local sourcepath = string.format("%s/%s.c", modpath, module)
  local binpath = string.format("%s/%s.so", modpath, module)

  local binexists = io.open(binpath)

  if not binexists or (binexists and lfs.attributes(sourcepath).change > lfs.attributes(binpath).change ) then
    io.popen(string.format("cc -I/usr/include/ -I/usr/include/lua%s/ -fPIC -shared -o %s %s %s", lua_version, binpath, sourcepath, table.concat(libs, " ")))
    io.popen(string.format("chown %s:%s %s", user, group, binpath))
    io.popen(string.format("chmod 600 %s", binpath))
  end
end

return compile