init_by_lua_block {

local dataloader		= require "dataloader"
local logger			= require "logger"
local cjson			= require "cjson"

local use_proxies		= {% if has_value("BLOCK_PROXIES", "yes") %}true{% else %}false{% endif +%}
local use_abusers		= {% if has_value("BLOCK_ABUSERS", "yes") %}true{% else %}false{% endif +%}
local use_tor_exit_nodes	= {% if has_value("BLOCK_TOR_EXIT_NODE", "yes") %}true{% else %}false{% endif +%}
local use_user_agents		= {% if has_value("BLOCK_USER_AGENT", "yes") %}true{% else %}false{% endif +%}
local use_referrers		= {% if has_value("BLOCK_REFERRER", "yes") %}true{% else %}false{% endif +%}
local use_crowdsec		= {% if has_value("USE_CROWDSEC", "yes") %}true{% else %}false{% endif +%}

if use_proxies then
	dataloader.load_ip("/etc/nginx/proxies.list", ngx.shared.proxies_data)
end

if use_abusers then
	dataloader.load_ip("/etc/nginx/abusers.list", ngx.shared.abusers_data)
end

if use_tor_exit_nodes then
	dataloader.load_ip("/etc/nginx/tor-exit-nodes.list", ngx.shared.tor_exit_nodes_data)
end

if use_user_agents then
	dataloader.load_raw("/etc/nginx/user-agents.list", ngx.shared.user_agents_data)
end

if use_referrers then
	dataloader.load_raw("/etc/nginx/referrers.list", ngx.shared.referrers_data)
end

if use_crowdsec then
	local cs = require "crowdsec.CrowdSec"
	local ok, err = cs.init("/etc/nginx/crowdsec.conf")
	if ok == nil then
		logger.log(ngx.ERR, "CROWDSEC", err)
		error()
	end
	logger.log(ngx.ERR, "CROWDSEC", "*NOT AN ERROR* initialisation done")
end

-- Load plugins
ngx.shared.plugins_data:safe_set("plugins", nil, 0)
local p = io.popen("find /opt/bunkerized-nginx/plugins -maxdepth 1 -type d ! -path /opt/bunkerized-nginx/plugins")
for dir in p:lines() do
	-- read JSON
	local file = io.open(dir .. "/plugin.json")
	if file then
		-- store settings
		local data = cjson.decode(file:read("*a"))
		for k, v in pairs(data.settings) do
			ngx.shared.plugins_data:safe_set(data.id .. "_" .. k, v, 0)
		end
		file:close()
		-- store plugin
		local plugins, flags = ngx.shared.plugins_data:get("plugins")
		if plugins == nil then
			ngx.shared.plugins_data:safe_set("plugins", data.id, 0)
		else
			ngx.shared.plugins_data:safe_set("plugins", plugins .. " " .. data.id, 0)
		end
		logger.log(ngx.ERR, "PLUGINS", "*NOT AN ERROR* plugin " .. data.name .. "/" .. data.version .. " has been loaded")
	else
		logger.log(ngx.ERR, "PLUGINS", "Can't load " .. dir .. "/plugin.json")
	end

end
p:close()

}
