public_ports = node['iptables']['public_ports']
private_ports = node['iptables']['private_ports']
ssh_source_ips = node['iptables']['ssh_source_ip']
ip_blacklists_databag = node['iptables']['ip_blacklists_databag']
ip_blacklists_databag_item = node['iptables']['ip_blacklists_databag_item']

ip_blacklists_urls = node['iptables']['ip_blacklists_urls']
ip_blacklists_blocks = []
ip_blacklists_urls.each do |_ip_blacklist_url_name, ip_blacklist_url|
  @http = Chef::HTTP::Simple.new(ip_blacklist_url)
  ip_blacklists_block = @http.get(ip_blacklist_url)
  ip_blacklists_block = ip_blacklists_block.gsub('$IPTABLES ', '')
  ip_blacklists_block = ip_blacklists_block.gsub('--log-level INFO', '--log-level info')

  ip_blacklists_blocks << ip_blacklists_block
end

blacklist_ips = []
begin
  blacklist_ips = data_bag_item(ip_blacklists_databag, ip_blacklists_databag_item)['ips']
rescue
  Chef::Log.warn("Cannot find item #{ip_blacklists_databag_item} \
  for databag #{ip_blacklists_databag}; skipping IP blacklisting")
end

template '/etc/sysconfig/iptables' do
  source 'network/iptables.erb'
  owner 'root'
  group 'root'
  mode 00664
  variables(
    public_ports: public_ports,
    private_ports: private_ports,
    ssh_source_ips: ssh_source_ips,
    blacklist_ips: blacklist_ips,
    ip_blacklists_blocks: ip_blacklists_blocks
  )
  notifies :restart, 'service[iptables]', :delayed
end

service 'iptables' do
  action :nothing
end
