local sleep_secs=15

local args = table.pack(...)
if args[1] ~= nil then sleep_secs = args[1] end

function create_state()
  local try = 0
  local lastconns = 0

  while true do
    if lastconns == core.get_info()["CumConns"] then
      try = try+1
    end

    local s = core.tcp()
    local c = s:connect("127.0.0.1:9990")
    local sent = s:send("show servers state\n")
    local content,err = s:receive("*a")
    s:close()

    if content ~= nil then
      if #content>0 then
        local f = io.open("/var/run/haproxy.state","w")
        f:write(content)
        io.close(f)
      end
    end

    lastconns = core.get_info()["CumConns"]

    if try == 10 then
      local msg = "Worker with pid ".. core.get_info()["Pid"] .. " exited for create_state task"
      print(msg)
      core.done(msg)
    end

    core.sleep(sleep_secs)
  end
end

core.register_task(create_state)