ip_blacklists_databag = node['firewalld']['ip_blacklists_databag']
ip_blacklists_databag_item = node['firewalld']['ip_blacklists_databag_item']
ip_blacklists_url = node['firewalld']['ip_blacklists_urls']

begin
  ips = data_bag_item(ip_blacklists_databag, ip_blacklists_databag_item)

  ips['ips'].each do |ip|
    firewalld_rich_rule "reject-#{ip}" do
      source_address   ip
      firewall_action  'reject'
    end
  end
rescue
  Chef::Log.warn("Cannot find item #{ip_blacklists_databag_item} \
  for databag #{ip_blacklists_databag}; skipping IP blacklisting")
end

# Blacklist all IPs from external URLs
# Implemented https://w3.alfresco.com/confluence/pages/viewpage.action?pageId=9077393
ip_blacklists_url.each do |ip_blacklist_url_name, ip_blacklist_url|
  remote_file "#{Chef::Config[:file_cache_path]}/#{ip_blacklist_url_name}" do
    source ip_blacklist_url
  end
  execute "blacklist-ips-from-url-#{ip_blacklist_url_name}" do
    command "cat #{Chef::Config[:file_cache_path]}/#{ip_blacklist_url_name} | \
            grep 'LOGNDROP' | \
            grep 'ETBLOCKLIST' | \
            awk '{print $7}' | \
            xargs -I % firewall-cmd --add-rich-rule=\"rule family=ipv4 source address=% reject\""
    not_if  "test -f /tmp/#{ip_blacklist_url_name}.run"
  end
  file "/tmp/#{ip_blacklist_url_name}.run" do
    action :create
    content ''
  end
end
